C# Knowledge base

Class and Object:

Class:
A Class is a user defined datatype which contains the variables, properties and methods in it. A class defines the abstract characteristics of a thing (object), including its characteristics (its attributes, fields or properties) and the thing's behaviors (the things it can do, or methods, operations or features). One might say that a class is a blueprint or factory that describes the nature of something. Collectively, the properties and methods defined by a class are called members.

Object:
Object is an instance of a class. The instance is the actual object created at run-time. The object consists of state and the behavior that's defined in the object's classes

 

C# supports several different kinds of statements are
·         Block statements
·         Declaration statements
·         Expression statements
·         Selection statements
·         Iteration statements
·         Jump statements
·         Try catch statements
·         Checked and unchecked
·         Lock statement

 

var:

It means that the type of the local being declared will be inferred by the compiler: 

// This statement:
var foo = "bar";
// Is equivalent to this statement:
string foo = "bar";

var does not define a variable to be of a dynamic type. So this is NOT legal:

var foo = "bar";
foo = 1; // Compiler error, the foo variable holds strings, not int

var  has only two uses:
  1. It requires less typing to declare variables, especially when declaring a variable as a nested generic type.
  2. It must be used when storing a reference to an object of an anonymous type, because the type name cannot be known in advance: var foo = new { Bar = "bar" };
You cannot use var as the type of anything but locals. So you can't use the keyword var to declare field/property/parameter/return types.


out and ref:

ref parameter is both input and o/p parameter
out parameter is only output parameter

As ref parameter treated as input parameter too, ref requires that the variable be initialized before being passed; otherwise you will receive compiler error.

As out parameter treated only as output parameter, out arguments need not be initialized prior to being passed, the calling method is required to assign a value before the method returns.


“is” and “as” Operators:

The is operator checks whether an object is compatible with a given type, and the result of the evaluation is a Boolean: true or false. The is operator will never throw an exception.
An is expression evaluates to true if both of the following conditions are met: 

·         expression is not null
·         expression can be cast to type

The as operator is like a cast except that it yields null on conversion failure instead of raising an exception. More formally, an expression of the form:

Employee e = obj as Employee;

is equivalent to:

Employee e = obj is Employee ? (Employee)obj : (Employee)null;

sealed Keyword

In order to prevent a class in C# from being inherited, the keyword sealed is used. Thus a sealed class may not serve as a base class of any other class. It is also obvious that a sealed class cannot be an abstract class. Code below...
//C# Example
sealed class ClassA
{
    public int x;
    public int y;
}
No class can inherit from ClassA defined above. Instances of ClassA may be created and its members may then be accessed, but nothing like the code below is possible...
class DerivedClass : ClassA { } // Error

Implementation inheritance and interface inheritance

When a class is derived from another class in such a way that it will inherit all its members to its corresponding derived class, then it is implementation inheritance. 
When a class inherits only the signatures of the functions from its corresponding base class, then it is interface inheritance.

Nullable Types in .Net

In .Net Framework 2.0, value types can be extended to take either their normal values or a null value. Such an extension is called a nullable type.
Nullable type is constructed from the generic Nullable structure. By having this feature, you can submit null values to you database table field normally, like submitting a null DateTime value to a datetime field in your database table.
int? id = null;
if (id.HasValue) // if id is not null
{
            //...do something
}
else // if id is null
{
            //... do something
}

Null-Coalescing Operator in .NET 2.0
Usually we use ternary operator as below:

string name = null;
Console.WriteLine(name == null ? "No name" : name);

It is a replacement for ternary conditional operator ?:

string name = null;
Console.WriteLine(name ?? "No name");


string a = null;
int? b = null;

Console.WriteLine(a ?? "tab");
Console.WriteLine(b ?? 100);
Console.ReadKey();


Serialization

Serialization is the process of converting an object into a stream of bytes.
De-serialization is the opposite process of creating an object from a stream of bytes.
Serialization / De-serialization is mostly used to transport objects.


using statement
The using statement is used to obtain a resource, execute a statement, and then dispose of that resource.



Delegate
Delegates are a type-safe, object-oriented implementation of function pointers and are used in many situations where a component needs to call back to the component that is using it.

Constants, ReadOnly and Static
·         Constants: The value can’t be changed.
·         Read-only: The value will be initialized only once from the constructor of the class or at declaration level.
·         Static: Value can be initialized once.


String keyword and System.String Class

String keyword is an alias for System.String class. Therefore, System.String and string keyword are the same, and you can use whichever naming convention you prefer. The String class provides many methods for safely creating, manipulating, and comparing strings.

Regex.Match searches strings based on a pattern. It isolates part of a string based on the pattern specified. It requires that you use the text-processing language for the pattern. It proves to be useful and effective in many C# programs.

The System.Text.RegularExpressions namespace contains the Regex class used to form and evaluate regular expressions. The Regex class contains static methods used to compare regular expressions against strings.

string emailId = "tab@email.com";
string regEmail = @"^((([\w]+\.[\w]+)+)|([\w]+))@(([\w]+\.)+)([A-Za-z]{1,3})$";

bool isM = Regex.IsMatch(emailId, regEmail);

if (isM)
{
Console.WriteLine("Email Id is verified.");
}
else
{
Console.WriteLine("Invalid Email Id.");
}

Match m = Regex.Match(emailId, regEmail, RegexOptions.IgnoreCase);

Console.WriteLine(m.Success);
Console.WriteLine(m.Value);


To learn and create regex expressions, download Espresso regex tool from http://www.ultrapico.com/ExpressoDownload.htm. Espresso by UltraPico is a free Regular Expression Editor which you can use to build and test your regular expressions.


Event
An event is a member that enables a class or object to provide notifications. An event is declared like a field except that the declaration includes an event keyword and the type must be a delegate type.

·         An event is an action performed based on another method of the program.
·         An event is a delegate type class member that is used by an object or a class to provide a notification to other objects that an event has occurred.
·         An event can be declared with the help of the event keyword.

// Define a delegate
public delegate void LogHandler(string message);

// Define an Event based on the above Delegate
public event LogHandler Log;

Multicast delegates
Each delegate object holds reference to a single method. However, it is possible for a delegate object to hold references of and invoke multiple methods. Such delegate objects are called multicast delegates or combinable delegates.

Difference between Array-List and Array.
·         Arrays are strongly typed
·         Array-Lists are not strongly typed.
·         Elements in Arrays have to be of same data type (int, string, double, char, bool…).
·         Elements in Array-List can have a combination of combined data types or single data type. Note: If Array-List has combined data types then type cast is must.
·         Arrays are fixed specified length size therefore they cannot be resize dynamically during runtime.
·         Array-List can resize dynamically during runtime



Difference between Dictionary  and Hashtable.

·         Hashtable is threadsafe and while Dictionary is not.
·         Dictionary is type safe which means that the values need not be boxed while Hashtable values need to be boxed or unboxed because it stores the values and keys as objects. 
·         When you try to get the value of key which does not exists in the collection, the dictionary throws an exception of 'KeyNotFoundException' while hashtable returns null value.
·         When using large collection of key value pairs hashtable would be considered more efficient than dictionary.
·         When we retrieve the record in collection the hashtable does not maintain the order of entries while dictionary maintains the order of entries by which entries were added.
·         Dictionary relies on chaining whereas Hashtable relies on rehashing.

There is an alternative in .Net 4.0 for a Dictionary that is called ConcurrentDictionary<TKey, TValue>. More about ConcurrentDictionary, visit http://msdn.microsoft.com/en-us/library/dd287191.aspx and http://msdn.microsoft.com/en-us/library/dd997369.aspx.

ReadOnly and Const difference


Both are meant for constant values. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in constructor.

·         A const cannot be static, while readonly can be static.
·         A const need to be declared and initialized at declaration only, while a readonly can be initialized at declaration or by the code in the constructor.
·         A const's value is evaluated at design time, while a readonly's value is evaluated at runtime.

Static Constructor

Yes, a class can have static constructor. Static constructors are called automatically, immediately before any static fields are accessed, and are generally used to initialize static class members. It is called automatically before the first instance is created or any static members are referenced. Static constructors are called before instance constructors. 

Abstract Classes and Interfaces

·         Abstract classes can have implementations for some of its members, but the interface can't have implementation for any of its members.
·         Interfaces cannot have fields where as an abstract class can have fields.
·         An interface can inherit from another interface only and cannot inherit from an abstract class, where as an abstract class can inherit from another abstract class or another interface.
·         A class can inherit from multiple interfaces at the same time, where as a class cannot inherit from multiple classes at the same time.
·         Abstract class members can have access modifiers where as interface members cannot have access modifiers.

Abstract Method and Virtual Method


An Abstract method does not provide an implementation and forces overriding to the deriving class (unless the deriving class also an abstract class), where as the virtual method has an implementation and leaves an option to override it in the deriving class. Thus Virtual method has an implementation & provides the derived class with the option of overriding it. Abstract method does not provide an implementation & forces the derived class to override the method.

Comments

Popular posts from this blog

Data Bound Controls in ASP.Net - Part 4 (FormView and DetailsView controls)

JavaScript - ES2015 (aka ES6)

The Clickjacking attack and X-Frame-Options