C# 4.0-Dynamic Data Type, Difference between var and dynamic

November 21, 2011

C# 4.0-Dynamic Data Type, Difference between var and dynamic

 
http://www.facebook.com/plugins/like.php?href=http://www.dotnetjalps.com/2009/11/c-40-dynamic-data-type-difference.html&layout=standard&show_faces=false&width=90&action=like&font=arial&colorscheme=light inShare0
C# 4.0 introduces a new keyword called ‘Dynamic‘. It can consume any object anything. Let’s see some examples for that.dynamic intExample = 1;
Response.Write(intExample);dynamic floatExample = 2.5;
Response.Write(floatExample);

dynamic stringExample = “DotNetJaps”;
Response.Write(stringExample);

 

It will print out put on web page as following.

C#-4.0-Dynamic-Keyword-Diffrence-Between-Var-And-Dynamic-Type

Now, you will have question what’s new in that. It could be also done with var keyword . Yes, you can do same thing with var but dynamic keyword is slightly different then var keyword.

Diffrence between var and dynamic keyword:

var keyword will know the value assigned to it at compile time while dynamic keyword will resolve value assigned to it at run time. I know you guys don’t believe me without example. So let’s take example of string.

string s = “DotNetJaps-A Blog for asp.net,C#.net,VB.NET”;
var varstring=s;
Response.Write(varstring.MethodDoesnotExist());

 

Now try to compile above code it will not compile and it gives a error that ‘string’ does not contain a definition for ‘MethodDoesnotExist’ and no extension method ‘MethodDoesnotExist’ accepting a first argument of type ‘string’ could be found (are you missing a using directive or an assembly reference?’. So var keyword knows that what value or object or anything assigned to it. Now lets try to compile same code with dynamic example like following.string s = “DotNetJaps-A Blog for asp.net,C#.net,VB.NET”;
dynamic varstring=s;
Response.Write(varstring.MethodDoesnotExist());

 

This will compile. So it is the difference between dynamic and var keyword. With dynamic keyword anything assigned to it like property,objects operators anything that will be determined at compile time. It can be useful while we are doing programming with com,JavaScript which can have runtime properties.


C# Singleton Pattern

November 21, 2011

Singleton Pattern in C#

Hi,
This piece of code will explain how to implement the Singleton pattern when we create a class.

    public class MySingleTon
    {
        private static MySingleTon singleTonObject;
        // private constructor. This will avoid creating object using new keyword
        private MySingleTon()
        {

        }
        // public method which will be called
        public void GetName()
        {
            Console.WriteLine("Brainstorming Guy");
        }
        public static MySingleTon CreateInstance()
        {
            // this object will be used with lock, so that it will be always one thread which will be executing the code
            object myObject = new object();
            // put a lock on myObject. We won't be able to use singleTonObject becuase it will be null. lock is to make the object thread safe.
            // lock can't be worked with null objects.
            lock (myObject)
            {
                // check whether the instance was there. If it's not there, then create an instance.
                if (singleTonObject == null)
                    singleTonObject = new MySingleTon();
            }
            return singleTonObject;
        }
    }

You can get an instance and you can make a call as given below.

            MySingleTon myObject = MySingleTon.CreateInstance();
            myObject.GetName();
            myObject = MySingleTon.CreateInstance();
            myObject.GetName();

When you execute the above piece of code, you can note that when the first time CreateInstance method is called, it will create an instance. But when you make a second call, it will check whether instance exists there and if it exists, it will return the same instance.
I placed comments in almost all the lines of the singleton class.


C# Static Class

November 21, 2011

Basic about Static Class

 
Overview
Static classes and class members are used to create data and functions that can be accessed without creating an instance of the class
Characteristic of static class .Net 2.0
  • Static class allows only static members
  • Static classes can not be instantiated
  • Static classes are sealed so they can not be inherited
  • Static classes can not allow derive the class or interfaces
  • Static class doesn’t allow instance ( non static ) members

All variables, methods inside static class are static

Static Classes


A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.

Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.

The main features of a static class are:

Creating a static class is therefore much the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated.

The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.

Static classes are sealed and therefore cannot be inherited. Static classes cannot contain a constructor, although it is still possible to declare a static constructor to assign initial values or set up some static state.

 

 

—————–

 

 

Static classes can’t be instantiated in the first place, so even if you could declare non-static (instance) members, they can never be accessed. Since there really isn’t a point allowing it for that reason, the language simply prohibits it.

Bear in mind that static classes are just the classes, while there are two things that are directly related to non-static classes: the classes themselves, and the instances/objects of the classes.

A non-static class can have both static and non-static members so that the static members apply to the class, whereas the non-static members apply to the instances of that class.

 
   
feedback
 

 

Static class can’t contain non-static members because by definition it can’t be instantiated so there’s no possibility to use these members.

However, static members in non-static class can be used without having class instance – a bit different scenario, i.e. for utility methods or factory methods.

 
 
 

 

Static class is just a handy constraint to ensure the class doesn’t accidentally contain non-static members. It belies programmer’s intention on how that class should be used. It says: “This class should not be instantiated”.

You can have classes with static members and non-static members combined, which becomes a non-static class. All you need to do is to remove the static keyword from class definition. And that would give a different message about programmer’s intention on how the class should be used.

The only place where a static class and a non-static class makes a difference is that extension methods must be in a static class.


Example of Polymorphism in .Net

November 21, 2011

Example of Polymorphism in .Net

 

 http://dotnetguts.blogspot.com/2007/07/example-of-polymorphism-in-net.html

Dashboards from Excel Charts and Ranges
You and your users can design dashboards, reports, charts, and models in Excel rather than hard to learn developer tools and you can easily deploy them with SpreadsheetGear for .NET.

Example of Polymorphism in .Net

What is Polymorphism?
Polymorphism means same operation may behave differently on different classes.
Example of Compile Time Polymorphism: Method Overloading
Example of Run Time Polymorphism: Method Overriding

Example of Compile Time Polymorphism

Method Overloading
- Method with same name but with different arguments is called method overloading.
- Method Overloading forms compile-time polymorphism.
- Example of Method Overloading:
class A1
{
void hello()
{ Console.WriteLine(“Hello”); }

void hello(string s)
{ Console.WriteLine(“Hello {0}”,s); }
}

Example of Run Time Polymorphism

Method Overriding
- Method overriding occurs when child class declares a method that has the same type arguments as a method declared by one of its superclass.
- Method overriding forms Run-time polymorphism.
- Note: By default functions are not virtual in C# and so you need to write “virtual” explicitly. While by default in Java each function are virtual.
- Example of Method Overriding:
Class parent
{
virtual void hello()
{ Console.WriteLine(“Hello from Parent”); }
}

Class child : parent
{
override void hello()
{ Console.WriteLine(“Hello from Child”); }
}

static void main()
{
parent objParent = new child();
objParent.hello();
}
//Output
Hello from Child.

 

 

C# Interface Abstract

November 21, 2011

http://mycodelines.wordpress.com/2009/09/01/in-which-scenario-we-use-abstract-classes-and-interfaces/

 

In which scenario we use Abstract Classes and Interfaces

Posted by Lakshmi Sravanthi Chowdam on September 1, 2009

Interface:

–> If your child classes should all implement a certain group of methods/functionalities but each of the child classes is free to provide its own implementation then use interfaces.

For e.g. if you are implementing a class hierarchy for vehicles implement an interface called Vehicle which has properties like Colour MaxSpeed etc. and methods like Drive(). All child classes like Car Scooter AirPlane SolarCar etc. should derive from this base interface but provide a seperate implementation of the methods and properties exposed by Vehicle.

–> If you want your child classes to implement multiple unrelated functionalities in short multiple inheritance use interfaces.

For e.g. if you are implementing a class called SpaceShip that has to have functionalities from a Vehicle as well as that from a UFO then make both Vehicle and UFO as interfaces and then create a class SpaceShip that implements both Vehicle and UFO .

Abstract Classes

–> When you have a requirement where your base class should provide default implementation of certain methods whereas other methods should be open to being overridden by child classes use abstract classes.

For e.g. again take the example of the Vehicle class above. If we want all classes deriving from Vehicle to implement the Drive() method in a fixed way whereas the other methods can be overridden by child classes. In such a scenario we implement the Vehicle class as an abstract class with an implementation of Drive while leave the other methods / properties as abstract so they could be overridden by child classes.

–> The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.

For example a class library may define an abstract class that is used as a parameter to many of its functions and require programmers using that library to provide their own implementation of the class by creating a derived class.

Use an abstract class

  • When creating a class library which will be widely distributed or reused—especially to clients, use an abstract class in preference to an interface; because, it simplifies versioning. This is the practice used by the Microsoft team which developed the Base Class Library. ( COM was designed around interfaces.)
  • Use an abstract class to define a common base class for a family of types.
  • Use an abstract class to provide default behavior.
  • Subclass only a base class in a hierarchy to which the class logically belongs.

 

Use an interface

  • When creating a standalone project which can be changed at will, use an interface in preference to an abstract class; because, it offers more design flexibility.
  • Use interfaces to introduce polymorphic behavior without subclassing and to model multiple inheritance—allowing a specific type to support numerous behaviors.
  • Use an interface to design a polymorphic hierarchy for value types.
  • Use an interface when an immutable contract is really intended.
  • A well-designed interface defines a very specific range of functionality. Split up interfaces that contain unrelated functionality.

 ————-

 

 

http://www.dotnetperls.com/abstract

 

http://www.dotnetissues.com/2011/06/code-example-for-interface-and-abstract.html

 

 http://www.codeproject.com/KB/cs/jmabstractclasses.aspx

 

Introduction

Abstract classes are one of the essential behaviors provided by .NET. Commonly, you would like to make classes that only represent base classes, and don�t want anyone to create objects of these class types. You can make use of abstract classes to implement such functionality in C# using the modifier ‘abstract‘.

An abstract class means that, no object of this class can be instantiated, but can make derivations of this.

An example of an abstract class declaration is:

Collapse | Copy Code
abstract class absClass
{
}

An abstract class can contain either abstract methods or non abstract methods. Abstract members do not have any implementation in the abstract class, but the same has to be provided in its derived class.

An example of an abstract method:

Collapse | Copy Code
abstract class absClass
{
  public abstract void abstractMethod();
}

Also, note that an abstract class does not mean that it should contain abstract members. Even we can have an abstract class only with non abstract members. For example:

Collapse | Copy Code
abstract class absClass
{
    public void NonAbstractMethod()
    {
        Console.WriteLine("NonAbstract Method");
    }
}

A sample program that explains abstract classes:

Collapse | Copy Code
using System;

namespace abstractSample
{
      //Creating an Abstract Class
      abstract class absClass
      {
            //A Non abstract method
            public int AddTwoNumbers(int Num1, int Num2)
            {
                return Num1 + Num2;
            }

            //An abstract method, to be
            //overridden in derived class
            public abstract int MultiplyTwoNumbers(int Num1, int Num2);
      }

      //A Child Class of absClass
      class absDerived:absClass
      {
            [STAThread]
            static void Main(string[] args)
            {
               //You can create an
               //instance of the derived class

               absDerived calculate = new absDerived();
               int added = calculate.AddTwoNumbers(10,20);
               int multiplied = calculate.MultiplyTwoNumbers(10,20);
               Console.WriteLine("Added : {0}, 
                       Multiplied : {1}", added, multiplied);
            }

            //using override keyword,
            //implementing the abstract method
            //MultiplyTwoNumbers
            public override int MultiplyTwoNumbers(int Num1, int Num2)
            {
                return Num1 * Num2;
            }
      }
}

In the above sample, you can see that the abstract class absClass contains two methods AddTwoNumbers and MultiplyTwoNumbers. AddTwoNumbers is a non-abstract method which contains implementation and MultiplyTwoNumbers is an abstract method that does not contain implementation.

The class absDerived is derived from absClass and the MultiplyTwoNumbers is implemented on absDerived. Within the Main, an instance (calculate) of the absDerived is created, and calls AddTwoNumbers and MultiplyTwoNumbers. You can derive an abstract class from another abstract class. In that case, in the child class it is optional to make the implementation of the abstract methods of the parent class.

Example

Collapse | Copy Code
//Abstract Class1
abstract class absClass1
{
    public abstract int AddTwoNumbers(int Num1, int Num2);
    public abstract int MultiplyTwoNumbers(int Num1, int Num2);
}

//Abstract Class2
abstract class absClass2:absClass1
{
    //Implementing AddTwoNumbers
    public override int AddTwoNumbers(int Num1, int Num2)
    {
        return Num1+Num2;
    }
}

//Derived class from absClass2
class absDerived:absClass2
{
    //Implementing MultiplyTwoNumbers
    public override int MultiplyTwoNumbers(int Num1, int Num2)
    {
        return Num1*Num2;
    }
}

In the above example, absClass1 contains two abstract methods AddTwoNumbers and MultiplyTwoNumbers. The AddTwoNumbers is implemented in the derived class absClass2. The class absDerived is derived from absClass2 and the MultiplyTwoNumbers is implemented there.

Abstract properties

Following is an example of implementing abstract properties in a class.

Collapse | Copy Code
//Abstract Class with abstract properties
abstract class absClass
{
    protected int myNumber;
    public abstract int numbers
    {
        get;
        set;
    }
}

class absDerived:absClass
{
    //Implementing abstract properties
    public override int numbers
    {
        get
        {
            return myNumber;
        }
        set
        {
            myNumber = value;
        }
    }
}

In the above example, there is a protected member declared in the abstract class. The get/set properties for the member variable myNumber is defined in the derived class absDerived.

Important rules applied to abstract classes

An abstract class cannot be a sealed class. I.e. the following declaration is incorrect.

Collapse | Copy Code
//Incorrect
abstract sealed class absClass
{
}

Declaration of abstract methods are only allowed in abstract classes.

An abstract method cannot be private.

Collapse | Copy Code
//Incorrect
private abstract int MultiplyTwoNumbers();

The access modifier of the abstract method should be same in both the abstract class and its derived class. If you declare an abstract method as protected, it should be protected in its derived class. Otherwise, the compiler will raise an error.

An abstract method cannot have the modifier virtual. Because an abstract method is implicitly virtual.

Collapse | Copy Code
//Incorrect
public abstract virtual int MultiplyTwoNumbers();

An abstract member cannot be static.

Collapse | Copy Code
//Incorrect
publpublic abstract static int MultiplyTwoNumbers();

Abstract class vs. Interface

An abstract class can have abstract members as well non abstract members. But in an interface all the members are implicitly abstract and all the members of the interface must override to its derived class.

An example of interface:

Collapse | Copy Code
interface iSampleInterface
{
  //All methods are automaticall abstract
  int AddNumbers(int Num1, int Num2);
  int MultiplyNumbers(int Num1, int Num2);
}

Defining an abstract class with abstract members has the same effect to defining an interface.

The members of the interface are public with no implementation. Abstract classes can have protected parts, static methods, etc.

A class can inherit one or more interfaces, but only one abstract class.

Abstract classes can add more functionality without destroying the child classes that were using the old version. In an interface, creation of additional functions will have an effect on its child classes, due to the necessary implementation of interface methods to classes.

The selection of interface or abstract class depends on the need and design of your project. You can make an abstract class, interface or combination of both depending on your needs.


C# Abstract Interface Notes

November 21, 2011

http://en.csharp-online.net/Should_I_use_an_abstract_class_or_an_interface%3F

Inheritance

A C# class may only subclass—inherit from—one other class. Therefore, by inheriting from (subclassing) an abstract class, the derived class has used up its ability to participate in a meaningful type hierarchy.

On the other hand, a class can implement—inherit from—any number of interfaces. And, it can still inherit from (subclass) a base class which makes sense.

[edit]

Single inheritance

C# supports single inheritance: C# does not support multiple inheritance from multiple classes like C++ does. But, by using abstract classes and interfaces, C# programs can achieve most of the same functionality without the confusion and maintenance problems associated with multiple inheritance.

[edit]

Value type polymorphism

.NET value types are objects descending from Object; but, they cannot inherit from other types. They can implement interfaces. Thus, primitives—such as Int32— can implement the IComparable interface, for example, making them comparable.

[edit]

Separation of contract and implementation

Interfaces separate the syntax rather than the semantic contract from the implementation. Classes can be designed to decouple the semantic contract from the implementation. For example, abstract classes can be separated in a different assembly than their concrete implementations.

[edit]

Versioning

An abstract class can contain an interface plus implementations. This simplifies versioning. An abstract class can be extended by adding new nonabstract methods with default implementations. Also, a convenience method is easily added to an abstract class.

An interface cannot be modified without breaking its contract with the classes which implement it. Once an interface has been shipped, its member set is permanently fixed. An API based on interfaces can only be extended by adding new interfaces.

[edit]

Design flexibility

Interfaces offer more design flexibility; precisely because, they can be implemented by any class regardless of its type hierarchy.

[edit]

Visual C# Best Practices

  • Use abstract classes and interfaces in combination to optimize your design trade-offs.
[edit]

Use an abstract class

  • When creating a class library which will be widely distributed or reused—especially to clients, use an abstract class in preference to an interface; because, it simplifies versioning. This is the practice used by the Microsoft team which developed the Base Class Library. (COM was designed around interfaces.)
  • Use an abstract class to define a common base class for a family of types.
  • Use an abstract class to provide default behavior.
  • Subclass only a base class in a hierarchy to which the class logically belongs.
[edit]

Use an interface

  • When creating a standalone project which can be changed at will, use an interface in preference to an abstract class; because, it offers more design flexibility.
  • Use interfaces to introduce polymorphic behavior without subclassing and to model multiple inheritance—allowing a specific type to support numerous behaviors.
  • Use an interface to design a polymorphic hierarchy for value types.
  • Use an interface when an immutable contract is really intended.
  • A well-designed interface defines a very specific range of functionality. Split up interfaces that contain unrelated functionality.

Summary

The following table compares the features of abstract classes and interfaces.

Abstract class Interface
Derived classes exhaust their single base class inheritance option. Classes can implement multiple interfaces without using up their base class option. But, there are no default implementations.
Cannot be instantiated except as part of subclasses. Only derived classes can call an abstract class constructor. Cannot be instantiated.
Defines abstract member signatures which derived classes must implement. Otherwise, the derived class itself will be abstract. Defines abstract member signatures—all of which—implementing classes must implement. Otherwise, a compiler error results.
New non-abstract members may be added that derived classes will inherit without breaking version compatibility. Extending an interface with new members breaks version compatibility.
Optionally, provide default (virtual) member implementation. All members are virtual and cannot provide implementations.
Can include data fields. Cannot include data fields. However, abstract properties may be declared

C# interface abstract classes

November 21, 2011

http://msdn.microsoft.com/en-us/library/scsyfw1d(v=vs.71).aspx

Recommendations for Abstract Classes vs. Interfaces
Visual Studio .NET 2003 The choice of whether to design your functionality as an interface or an abstract class (a MustInherit class in Visual Basic) can sometimes be a difficult one. An abstract class is a class that cannot be instantiated, but must be inherited from. An abstract class may be fully implemented, but is more usually partially implemented or not implemented at all, thereby encapsulating common functionality for inherited classes. For details, see Abstract Classes.

An interface, by contrast, is a totally abstract set of members that can be thought of as defining a contract for conduct. The implementation of an interface is left completely to the developer.

Both interfaces and abstract classes are useful for component interaction. If a method requires an interface as an argument, then any object that implements that interface can be used in the argument. For example:

Copy
 ’ Visual Basic
Public Sub Spin (ByVal widget As IWidget)
End Sub
// C#
public void Spin (IWidget widget)
{}
This method could accept any object that implemented IWidget as the widget argument, even though the implementations of IWidget might be quite different. Abstract classes also allow for this kind of polymorphism, but with a few caveats:

•Classes may inherit from only one base class, so if you want to use abstract classes to provide polymorphism to a group of classes, they must all inherit from that class.
•Abstract classes may also provide members that have already been implemented. Therefore, you can ensure a certain amount of identical functionality with an abstract class, but cannot with an interface.
Here are some recommendations to help you to decide whether to use an interface or an abstract class to provide polymorphism for your components.

•If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.
•If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.
•If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
•If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.
———

http://www.codeproject.com/KB/cs/abstractsvsinterfaces.aspx

Introduction

In this article along with the demo project I will discuss Interfaces versus Abstract classes. The concept of Abstract classes and Interfaces is a bit confusing for beginners of Object Oriented programming. Therefore, I am trying to discuss the theoretical aspects of both the concepts and compare their usage. And finally I will demonstrate how to use them with C#.

Background

An Abstract class without any implementation just looks like an Interface; however there are lot of differences than similarities between an Abstract class and an Interface. Let’s explain both concepts and compare their similarities and differences.

What is an Abstract Class?

An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.

What is an Interface?

An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn�t support multiple inheritance, interfaces are used to implement multiple inheritance.

Both Together

When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.

When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface. The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.

There are some similarities and differences between an interface and an abstract class that I have arranged in a table for easier comparison:

Feature Interface Abstract class
Multiple inheritance A class may inherit several interfaces. A class may inherit only one abstract class.
Default implementation An interface cannot provide any code, just the signature. An abstract class can provide complete, default code and/or just the details that have to be overridden.
Access Modfiers An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public An abstract class can contain access modifiers for the subs, functions, properties
Core VS Peripheral Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface. An abstract class defines the core identity of a class and there it is used for objects of the same type.
Homogeneity If various implementations only share method signatures then it is better to use Interfaces. If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.
Speed Requires more time to find the actual method in the corresponding classes. Fast
Adding functionality (Versioning) If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method. If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
Fields and Constants No fields can be defined in interfaces An abstract class can have fields and constrants defined

 

 


vbnet c# Keyword Differences

November 20, 2011

http://www.codeproject.com/KB/dotnet/vbnet_c__difference.aspx

Purpose VB.NET C#
Declare a variable Private, Public, Friend, Protected, Static1, Shared, Dim declarators (keywords include user-defined types and built-in types)
Declare a named constant Const const
Create a new object New, CreateObject() new
Function/method does not return a value Sub void
Overload a function or method (Visual Basic: overload a procedure or method) Overloads (No language keyword required for this purpose)
Refer to the current object Me this
Make a nonvirtual call to a virtual method of the current object MyClass n/a
Retrieve character from a string GetChar Function []
Declare a compound data type (Visual Basic: Structure) Structure <members> End Structure struct, class, interface
Initialize an object (constructors) Sub New() Constructors, or system default type constructors
Terminate an object directly n/a n/a
Method called by the system just before garbage collection reclaims an object7 Finalize destructor
Initialize a variable where it is declared
Collapse | Copy Code
Dim x As Long = 5
Collapse | Copy Code
Dim c As New _
   Car(FuelTypeEnum.Gas)
Collapse | Copy Code
// initialize to a value:
int x = 123;
// or use default 
// constructor:
int x = new int();
Take the address of a function AddressOf (For class members, this operator returns a reference to a function in the form of a delegate instance) delegate
Declare that an object can be modified asynchronously n/a volatile
Force explicit declaration of variables Option Explicit n/a. (All variables must be declared prior to use)
Test for an object variable that does not refer to an object obj = Nothing obj == null
Value of an object variable that does not refer to an object Nothing null
Test for a database null expression IsDbNull n/a
Test whether a Variant variable has been initialized n/a n/a
Define a default property Default by using indexers
Refer to a base class MyBase base
Declare an interface Interface interface
Specify an interface to be implemented Implements (statement) class C1 : I1
Declare a class Class <implementation> class
Specify that a class can only be inherited. An instance of the class cannot be created. MustInherit abstract
Specify that a class cannot be inherited NotInheritable sealed
Declare an enumerated type Enum <members> End Enum enum
Declare a class constant Const const (Applied to a field declaration)
Derive a class from a base class Inherits C2 class C1 : C2
Override a method Overrides override
Declare a method that must be implemented in a deriving class MustOverride abstract
Declare a method that can’t be overridden NotOverridable (Methods are not overridable by default.) sealed
Declare a virtual method, property (Visual Basic), or property accessor (C#, C++) Overridable virtual
Hide a base class member in a derived class Shadowing n/a
Declare a typesafe reference to a class method Delegate delegate
Specify that a variable can contain an object whose events you wish to handle WithEvents (Write code – no specific keyword)
Specify the events for which an event procedure will be called Handles (Event procedures can still be associated with a WithEvents variable by naming pattern.) n/a
Evaluate an object expression once, in order to access multiple members
Collapse | Copy Code
With objExpr 
  <.member>
  <.member> 
End With
n/a
Structured exception handling
Collapse | Copy Code
Try <attempt>
Catch
<handle errors>
Finally
<always execute>
End Try
try, catch, finally, throw
Decision structure (selection) Select Case ..., Case, Case Else, End Select switch, case, default, goto, break
Decision structure (if … then) If ... Then, ElseIf ... Then, Else, End If if, else
Loop structure (conditional) While, Do [While, Until] ..., Loop [While, Until] do, while, continue
Loop structure (iteration) For ..., [Exit For], Next
For Each ..., [Exit For,] Next
for, foreach
Declare an array
Collapse | Copy Code
Dim a() As Long
Collapse | Copy Code
int[] x = new int[5];
Initialize an array
Collapse | Copy Code
Dim a() As Long = {3, 4, 5}
Collapse | Copy Code
int[] x = new int[5] {
        1, 2, 3, 4, 5};
Reallocate array Redim n/a
Visible outside the project or assembly Public public
Invisible outside the assembly (C#/Visual Basic) or within the package (Visual J#, JScript) Friend internal
Visible only within the project (for nested classes, within the enclosing class) Private private
Accessible outside class and project or module Public public
Accessible outside the class, but within the project Friend internal
Only accessible within class or module Private private
Only accessible to current and derived classes Protected protected
Preserve procedure’s local variables Static n/a
Shared by all instances of a class Shared static
Comment code '
Rem
//, /* */ for multi-line comments
/// for XML comments
Case-sensitive? No Yes
Call Windows API Declare <API> use Platform Invoke
Declare and raise an event Event, RaiseEvent event
Threading primitives SyncLock lock
Go to Goto goto

CSharp Notes

August 24, 2010

1. Internet url regular expression

http(s)?://([w-]+.)+[w-]+(/[w- ./?%&=]*)?
Http or Https are required, when a lot of internet users don’t even know this protocol exists, as they think every url begins with www.
Some crazy urls (Visit Scotland I’m looking at you!) can have other characters not supported by this expression in them (i.e , or ;) .
So in order to get around these little issues I altered the expression a little (see below).
(http(s)?://)?([w-]+.)+[w-]+(/[w- ;,./?%&=]*)?

or

http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?
REg tool : http://www.c-sharpcorner.com/uploadfile/masief/regularexpvalidator08302005000634am/regularexpvalidator.aspx

———-
http://aspalliance.com/259

Ever try to force the “Download File” dialog in a clients’s browser window when you download files that may be supported with a MIME type? Here is an example that works with many versions of IE.

This example illustrates a simple technique to download files of any type from you web application to the client browser. In addition to setting the MIME types, the example shows how to force the Download File dialog that allows the user to either run or save the file, even if the file type would normally display in the browser’s window.
On my personal site (http://www.sharkcode.com ), I allow the user to download my resume in various formats including Microsoft Word, HTML, Rich Text and Plain Text. I found that for most users (with IE) the correct application was automatically used to view the document from within their browser (such as Word types like .doc). In all cases, however, I wanted the file to be saved to the client’s workstation, rather than simply being displayed by the browser. When I hosted my own site, I could do this by setting the HTTP Headers with “content-disposition” to force the Download File dialog. Now, using the .NET Response object, I can set these headers directly.

The basic ingredients of this example are quite simple and can be found in a Microsoft article at (http://support.microsoft.com/directory/article.asp?ID=KB;EN-US;q306654&lex).

The Microsoft article includes the following code snippet:

private void Page_Load(object sender, System.EventArgs e)
{
  //Set the appropriate ContentType.
  Response.ContentType = “Application/pdf”;
  //Get the physical path to the file.
  string FilePath = MapPath(“acrobat.pdf”);
  //Write the file directly to the HTTP content output stream.
  Response.WriteFile(FilePath);
  Response.End();
}
I used this example to write a simple method that accepts a file name as input and a boolean that will force the File Download dialog which allows the client to either run, or save this file to their local workstation.

private void DownloadFile( string fname, bool forceDownload )
{
  string path = MapPath( fname );
  string name = Path.GetFileName( path );
  string ext = Path.GetExtension( path );
  string type = “”;
  // set known types based on file extension 
  if ( ext != null )
  {
    switch( ext.ToLower() )
    {
    case “.htm”:
    case “.html”:
      type = “text/HTML”;
      break;
 
    case “.txt”:
      type = “text/plain”;
      break;
    
    case “.doc”:
    case “.rtf”:
      type = “Application/msword”;
      break;
    }
  }
  if ( forceDownload )
  {
    Response.AppendHeader( “content-disposition”,
        “attachment; filename=” + name );
  }
  if ( type != “” )  
    Response.ContentType = type;
  Response.WriteFile( path );
  Response.End();   
}
The first few lines of code simply convert the file name argument into a physical path (on the server) and get the various component parts of the name. I only handle the file extension of known types that I’m currently using, but this could be extended to support additional MIME types (see the Microsoft article).

If the forceDownload boolean is true, I use the Response.AppendHeader method to add the “content-disposition” which forces the File Download (save) dialog.

I didn’t find a lot of online help with the “content-disposition” header. In fact, it may even be on its way out in the future. But this currently works fine with IE 6 (and several prior version of IE upon which I’ve tested).
—————–

Merging datasets:

datatable1.Merge(datatable2) .It returns void

———-
ASP.NET File Upload: Workaround for File Size Too Large
add to web.config tag:
<system.web>
<httpRuntime maxRequestLength=”102400″ executionTimeout=”360″/>
</system.web>


Interview Questions C#

July 25, 2010

BON

1. what is the difference between view and sp

views cannot take input parameters
sp can take
2. function and sp
3. different objects in sql … table,sp,view
4. different objects in table .. index,keys
5. what is abstract,interfaces
what is the default inheritance used in dotnet
what is multiple and multilevel inheritance
can we inherit multiple interfaces for the same class
what is overriding and overloading

in three tier if u r hardcoding no. of parameters if in future if u r increasing the no. of parameters then how u will handle

in master page u r having a button. how u will raise that event in child control
difference cache and viewstate
what are the steps in reporting services in offline mode
ans :datasets (xsd) files.

6. what is singleton and how to create


Follow

Get every new post delivered to your Inbox.