Powered By Blogger

Tuesday, December 1, 2009

C# Tips

C#

Object: In computer science, an object, in the domain of object-oriented programming, usually means a compilation of attributes (object elements) and behaviors (methods) encapsulating an entity.
Classes are reference types; they are allocated on the Managed Heap. The Managed Heap is an area of memory that is managed by the Common Language Runtime, which has the ability to free unused memory blocks (objects) in a process known as Garbage Collection.

Access Modifier keywords: public, private, protected and internal.
Public: no restrictions on accessing public members.
Accessibility: Can be accessed by objects of the class.
Can be accessed by derived classes.
Private: Private members are accessible only within the body of the class or the struct in which they are declared.
Accessibility: Cannot be accessed by object.
Cannot be accessed by derived classes.
Protected: A protected member is accessible from within the class in which it is declared, and from within any class derived from the class that declared this member.
A protected member of a base class is accessible in a derived class only if the access takes place through the derived class type.
Accessibility: Cannot be accessed by object.
By derived classes.
Internal: The internal keyword is an access modifier for types and type members. We can declare a class as internal or its member as internal. Internal members are accessible only within files in the same assembly (.dll).
In other words, access is limited exclusively to classes defined within the current project assembly.
Accessibility: In same assembly (public) can be accessed by objects of the class
Can be accessed by derived classes
In other assembly (internal) cannot be accessed by object
Cannot be accessed by derived classes.
Protected internal: The protected internal accessibility means protected OR internal, not protected AND internal.
In other words, a protected internal member is accessible from any class in the same assembly, including derived classes.
The protected internal access modifier seems to be a confusing but is a union of protected and internal in terms of providing access but not restricting. It allows:
-Inherited types, even though they belong to a different assembly, have access to the protected internal members.
-Types that reside in the same assembly, even if they are not derived from the type, also have access to the protected internal members.

Class members: fields, properties, methods, constructors, destructor, indexers, constants, events, delegates and operators.

Struct: Similar to Class, A struct type is a value type that can contain constructors, constants, fields, methods, properties, indexers, operators, events, and nested types. By default it is sealed. There is no inheritance for structs as there is for classes. The struct type is suitable for representing lightweight objects such as Point, Rectangle, and Color.

Class Program
{
Struct Simple
{
public int Position;
public bool Exists;
public double LastValue;
} ;
static void Main ()
{
Simple s;
s.Position = 1;
s.Exists = false;
s.LastValue = 5.5;
}
}


Static class: a static class cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the class type. Ex: UtilityClass.MethodA ();
  • Contains only static members.
  • Cannot be instantiated.
  • Is sealed.
  • Cannot contain Instance Constructors.

static class CollegeRegistration
{
//All static member variables
static int nCollegeId; //College Id will be same for all the students studying
static string sCollegeName; //Name will be same
static string sColegeAddress; //Address of the college will also same
//Member functions
public static int GetCollegeId()
{
nCollegeId = 100;
return (nCollegeID);
}
//similarly implementation of others also.
}
public class student
{
int nRollNo;
string sName;
public GetRollNo()
{
nRollNo += 1;
return (nRollNo);
}
//similarly ....
public static void Main()
{ //Not required.
//CollegeRegistration objCollReg= new CollegeRegistration();
// .
int cid= CollegeRegistration.GetCollegeId();
string sname= CollegeRegistration.GetCollegeName();
}
}


Static member: A non-static class can contain static methods, fields, properties, or events. The static member is callable on a class even when no instance of the class has been created. The static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created. Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it is explicitly passed in a method parameter. We can’t use this keyword to access Static Members.

Abstract Class: -cannot be instantiated. - An abstract class is only to be sub-classed (inherited from). - A class may inherit only one abstract class, but may implement multiple numbers of Interfaces. - Abstract class methods may OR may not have an implementation.

Public abstract class Shape
{ //...Class implementation
Public abstract void Draw (int x, int y)
{ //this method mustn't be implemented here.
//If we do implement it, the result is a Syntax Error.
}
}
Public abstract class Shape2D: Shape
{
//...Class implementation //...you do not have to implement the method Draw (int x, int y)
}
Public class Circle: Shape2D
{
//here we should provide an implementation for Draw (int x, int y)
Public override void Draw (int x, int y)
{
//must do some work here
}
}


Abstract and Virtual Method:
When a base class declares a method as virtual, a derived class can override the method with its own implementation.
If a base class declares a member as abstract, that method must be overridden in any non-abstract class that directly inherits from that class.
An abstract method is a method without any method body. They are implicitly virtual in C#.

Abstract class MyAbs
{
public void NonAbMethod()
{
Console.WriteLine("Non-Abstract Method");
}
public abstract void AbMethod(); // An abstract method
}
class MyClass : MyAbs //must implement base class abstract methods
{
public override void AbMethod()
{
Console.WriteLine("Abstarct method");
}
}


An Interface contains only the signatures of methods, properties, events or indexers. A class or struct that implements the interface must implement the members of the interface that are specified in the interface definition.
Ex:

Interface ISampleInterface
{
Void SampleMethod ();
}
Class ImplementationClass: ISampleInterface
{
// Explicit interface member implementation:
Void ISampleInterface.SampleMethod ()
{
// Method implementation.
}
Static void Main ()
{
ISampleInterface obj = new ImplementationClass ();
Obj. SampleMethod ();
}
}

Sealed class: A sealed class cannot be used as a base class; it cannot also be an abstract class. By creating an instance we can use the methods in the Sealed Class.

class Program
{
public sealed class BaseClass
{
public void Display()
{
Console.WriteLine("This is a sealed class which can’t be further inherited");
}
}

public class Derived : BaseClass
{
// this Derived class can’t inherit BaseClass because it is sealed
}
static void Main(string[] args)
{
BaseClass obj = new BaseClass();
obj.Display();
Console.ReadLine();
}
}


Delegates: Delegates are used to pass methods as arguments to other methods. It allow programmer to encapsulate a reference to a method inside a delegate object. Delegates are type-safe, secure managed objects. This means that the runtime guarantees that a delegate points to a valid method, which further means that you get all the benefits of function pointers without any of the associated dangers, such as an invalid address or a delegate corrupting the memory of other objects.

class clsDelegate
{
public delegate int simpleDelegate (int a, int b);
public int addNumber(int a, int b)
{
return (a+b);
}
public int mulNumber(int a, int b)
{
return (a*b);
}
static void Main(string[] args)
{
clsDelegate clsDlg = new clsDelegate();
simpleDelegate addDelegate = new simpleDelegate(clsDlg.addNumber);
simpleDelegate mulDelegate = new simpleDelegate(clsDlg.mulNumber);
int addAns = addDelegate(10,12);
int mulAns = mulDelegate(10,10);
Console.WriteLine("Result by calling the addNum method using a delegate: {0}",addAns);
Console.WriteLine("Result by calling the mulNum method using a delegate: {0}",mulAns);
Console.Read();
}
}

Types: Single-Cast delegate and Multicast delegate.
A Single-cast delegate can call only one method at a time, whereas a Multicast delegate can call multiple methods at the same time.

Value type variables directly contain their values, which mean that the memory is allocated inline in whatever context the variable is declared.

There are two categories of value types: struct and enum.
A type that is defined as a class, delegate, array, or interface is a Reference type. At run time, when you declare a variable of a reference type, the variable contains the value null until you explicitly create an instance of the object by using the new operator.

A Generic type can be declared with one or more type parameters. Generic collection classes are called strongly-typed collections because the compiler knows the specific type of the collection's elements and can raise an error at compile-time if, for example, you try to add an integer to the strings object.

Namespaces: .NET Framework uses namespaces to organize its many classes. Namespaces are used to logically arrange classes, structs, interfaces, enum and delegates. One namespace can contain other namespaces also.

The enum keyword is used to declare an enumeration (a numbered list), a distinct type consisting of a set of named constants called the enumerator list.

enum Days {low, medium, high};

class EnumSwitch
{
Public Static Void Main ()
{
Volume myVolume = Volume. Medium;
Switch (myVolume)
{
Case Volume. Low:
Console.WriteLine("The volume has been turned Down.");
break;
Case Volume. Medium:
Console.WriteLine ("The volume is in the middle.");
break;
Case Volume. High:
Console.WriteLine ("The volume has been turned up.");
break;
}
Console.ReadLine (); .
}
}


Dictionary: A Dictionary (TKey, TValue) contains a collection of key/value pairs. Its Add method takes two parameters, one for the key and one for the value.

Dictionary students = new Dictionary ()
{
{ 111, new StudentName {FirstName="Sachin", LastName="Karnik", ID=211 }},
{ 112, new StudentName {FirstName="Dina", LastName="Salimzianova", ID=317 }},
{ 113, new StudentName {FirstName="Andy", LastName="Ruth", ID=198 }}
};


Boxing: Conversion of Value Types to Reference Types.
Ex: int32 x=10;
Object obj=x; //Implicit Boxing; No need to tell the compiler about boxing
Object obj= (Object) x; //Explicit Boxing;
Unboxing: Conversion of Reference Types to Value Types.
X= obj; //Implicit Unboxing

Constructors: Constructors are class methods that are executed when an object of a given type is created. Constructors have the same name as the class. They do not have return types, not even void. Constructor is invoked by the new operator immediately after memory is allocated for the new object.
A constructor that takes no parameters is called a default constructor. Default constructors are invoked whenever an object is instantiated using the new operator and no arguments are provided to new.
Constructors for struct types are similar to class constructors, but structs cannot contain an explicit default constructor because one is provided automatically by the compiler.
Note: There is always at least one constructor in every class. If you do not write a constructor, C# automatically provides one for you, this is called default constructor.

Destructor: A destructor is just opposite to constructor. It has same as the class name, but with prefix ~ (tilde). They do not have return types, not even void and therefore they cannot return values. Destructor is invoked whenever an object is about to be garbage collected
Finalize () Method of Object class
Each class in C# is automatically (implicitly) inherited from the Object class which contains a method Finalize (). This method is guaranteed to be called when your object is garbage collected (removed from memory). You can override this method and put here code for freeing resources that you reserved when using the object.

Method Overloading: Method with same name but with different arguments is called method overloading. Method Overloading forms compile-time polymorphism.

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


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.

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.

OOPS:
Polymorphism (Many Shapes): Polymorphism is briefly described as "one interface, many implementations. Polymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts.
There are two types of polymorphism one is compile time polymorphism and the other is run time polymorphism. Compile time polymorphism is functions and operators overloading. Runtime time polymorphism is done using inheritance and virtual functions.
Function Overloading: In case of compile time it is called function overloading. Two or more functions can have same name: different parameters or their data types. Compiler will select the right function depending on the type of parameters passed.
Operator Overloading: Operators can be overloaded in order to perform special functions with respect to the class. With the help of operator overloading standard operations such as +, - , *, etc can be applied on the objects of the class.
Encapsulation is the procedure of covering up of data and functions into a single unit. Ex: Delegate.
Inheritance enables you to create new classes that reuse, extend, and modify the behavior that is defined in other classes. The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. Inheritance is the mechanism which allows a class A to inherit properties of a class B. Note: A sealed class cannot be inherited. A sealed class is used primarily when the class contains static members. Note: Struct is implicitly sealed; so they cannot be inherited.
Partial Class: It is possible to split the definition of a class or a struct, or an interface over two or more source files. Each source file contains a section of the class definition, and all parts are combined when the application is compiled.
• when working on large projects, spreading a class over separate files allows multiple programmers to work on it simultaneously.
• when working with automatically generated source, code can be added to the class without having to recreate the source file. Visual Studio uses this approach when creating Windows Forms, Web Service wrapper code, and so on. You can create code that uses these classes without having to edit the file created by Visual Studio.
public partial class Employee
{
public void DoWork()
{
}
}
public partial class Employee
{
public void GoToLunch()
{
}
}
Casting: Converting between data types can be done explicitly using a cast, but in some cases, implicit conversions are allowed.
static void TestCasting(){
int i = 10;
float f = 0;
f = i; // An implicit conversion, no data will be lost.
f = 0.5F;
i = (int)f; // An explicit conversion. Information will be lost.
}
Difference between FOR and FOREACH: The FOR LOOP executes a statement or a block of statements repeatedly until a specified expression evaluates to false. There is need to specify the loop bounds (minimum or maximum).
The FOREACH statement repeats a group of embedded statements for each element in an array or an object collection. You do not need to specify the loop bounds minimum or maximum.

string [] n = new string[] {"test1", "test2"}
foreach(string a in n)
....
for(int i=0; i and XML documentation tag? Single line code example and multiple-line code example.
Is XML case-sensitive? Yes, so and are different elements.
Can you change the value of a variable while debugging a C# application? Yes, if you are debugging via Visual Studio.NET, just go to Immediate window.
What does Dispose method do with the connection object? Deletes it from the memory.
Is it possible to have different access modifiers on the get/set methods of a property? - No. The access modifier on a property applies to both its get and set assessors. What you need to do if you want them to be different is make the property read-only (by only providing a get accessor) and create a private/internal set method that is separate from the property.
How does one compare strings in C#? In the past, you had to call .ToString() on the strings when using the == or != operators to compare the strings’ values. That will still work, but the C# compiler now automatically compares the values instead of the references when the == or != operators are used on string types. If you actually do want to compare references, it can be done as follows:
if ((object) str1 == (object) str2) { }
What is the difference between const and static read-only? The difference is that static read-only can be modified by the containing class, but const can never be modified and must be initialized to a compile time constant. To expand on the static read-only case a bit, the containing class can only modify it: -- in the variable declaration (through a variable initializer).
-- in the static constructor (instance constructors if it's not static).
Is there any sample C# code for simple threading?
Some sample code follows: using System;
using System.Threading;
class ThreadTest
{
public void runme()
{
Console.WriteLine("Runme Called");
}
public static void Main(String[] args)
{
ThreadTest b = new ThreadTest();
Thread t = new Thread(new ThreadStart(b.runme));
t.Start();
}
}
Can you override private virtual methods? No, moreover, you cannot access private methods in inherited classes, have to be protected in the base class to allow any sort of access.
What is the .NET datatype that allows the retrieval of data by a unique key?
HashTable.
What is the difference between the Debug class and Trace class? Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds.
How can I get the ASCII code for a character in C#? Casting the char to an int will give you the ASCII value: char c = 'f'; System.Console.WriteLine((int)c); or for a character in a string: System.Console.WriteLine((int)s[3]); The base class libraries also offer ways to do this with the Convert class or Encoding classes if you need a particular encoding.
Can you allow a class to be inherited, but prevent the method from being over-ridden? Yes. Just leave the class public and make the method sealed.
What is the smallest unit of execution in .NET? An Assembly.
What is the maximum size of the textbox? 65536.
What does the term immutable mean? The data value may not be changed. Note: The variable value may be changed, but the original immutable data value was discarded and a new data value was created in memory.
What is the difference between Finalize() and Dispose()? Dispose() is called by as an indication for an object to release any unmanaged resources it has held.
Finalize() is used for the same purpose as dispose however finalize doesn’t assure the garbage collection of an object.
Dispose() operates determinalistically due to which it is generally preferred.
Difference between Debug class and Trace class? Debug class is used for debug builds while Trace class is used for both debug and release builds.