C#

Basic concepts in C#

Tuba Mansoor
Latest posts by Tuba Mansoor (see all)

Generics

Traditionally if we use collections like ArrayList to store our collection, the disadvantage is that these collections are not strongly typed which means they lead to performance penalty during boxing and unboxing. Arraylist expects an input of type object, so when you store something in an arraylist, boxing occurs. During retrieval unboxing takes place.

If we use arrays which are strongly typed, then the disadvantage is that they cannot grow in size once initialized.

The solution is to use generics. They are type safe like arrays and can grow in size like arraylist. There is no performance penalty for boxing and unboxing.

Below is a list of the non generic collection with their generic counterparts-

ArrayList -> List<T>

Hashtable -> Dictionary <Tkey, TValue>

Stack -> Stack<T>

Queue -> Queue<T>

SQL Injection

Suppose we have a textbox, and using ado.net we we execute a select statement as below:

See also  Microservices Pattern - Shared Data

select * from tblEmployees where employeeid = ‘txtbox.txt’

If the user inputs a delete statement in the textbox as below, then the query will be executed and the delete statement will work.

1; delete tblEmployees

The first way to avoid sql injection is by using parameterised queries. The advantage of using parameterised queries is that everything that the user inputs will be treated as parameter. So, the delete statement will also be treated as a parameter for employeeid.

Similarly we can use stored procedures too.

Integral type in C#

The following table from MSDN talks about the different integral types in C#.

Floating point numeric types

The following table has been referred from MSDN.

Verbatim identifier

Verbatim Identifier is @. Used to indicate that a string literal is to be interpreted as it is. For example

    string x = "c\r\r";
    Console.WriteLine(x);

Gives the output as ‘c’.

But using a verbatim identifier as below gives a different output.

string x = @"c\r\r";
Console.WriteLine(x);

Output

‘c\r\r’

Static keyword

If a variable is marked as static, then even though multiple objects of that given class are created,only one instance of that static variable will be created which will be shared by all the objects of that class. You cannot use this.variableName while using the variables.

Static methods can be called without creating objects.

Static constructors cannot have public modifiers. They are used to initialize static fields. Called before a static member is called. Called only once. Always called before instance constructors.

See also  C# LINQ Tutorial with Examples

Inheritance

If two classes have duplicate code, inheritance may be considered. With inheritance we can define a base class having some functionality and child classes that inherit from the base class can either inherit or override that functionality.

Method Hiding

Base class method can be overridden in child classes using new keyword. This is called as method hiding. Using new keyword in case of method hiding is not mandatory but preferred.

Even in case of method hiding, base class method can be invoked with any of the 3 methods:

  1. Using base keyword
public new void ChildMethod(){
   base.ParentMethod();
}

2. Typecast object into parent type.

ChildClass object = new ChildClass();
((ParentClass)object).ParentMethod();

3. Refer to a parentclass object.

ParentClass object = new ChildClass();
object.ParentMethod();

Polymorphism

If the reference of a parent type is given while the object is of child class, whether child or parent method is called depends upon whether method hiding is implemented or method overriding.

ParentClass object = new ChildClass();
object.ParentMethod();

Method Hiding:

In this case parent class method will be called.

Method Overriding:

In this case the method to be overridden is marked as ‘virtual’ in parent class and ‘override’ in child class. In case of method overriding child class method is called.

Thus we see that the same line of code can be call base class members or child class members, depending upon whether method hiding is used or method overriding. This is polymorphism. Some people also refer it as ‘Dynamic Polymorphism’. Method overloading is then referred to as ‘Static Polymorphism’.

See also  Angular Tutorial for Beginners - Part 1 : Getting Started

When the decision to which method to invoke is taken at runtime then Dynamic Polymorphism occurs. When the decision to invoke is decide at compile time, Static Polymorphism occurs.

Note that polymorphism does not occur only with methods. It can also be applied to other members like properties, events and indexers.

Method overloading:

Classes can have methods with same names provided they differ in the number of parameters, datatype of the parameters and their sequence. This is also known as static polymorphism.

Fields

A field is a variable of any type that is declared directly in a class or struct.

public DateTime date;

Properties

There maybe certain fields that we do not want to be changed or exposed, or we may want to run some logic before the value of that field is set. In that case properties are used.

private DateTime date;
public DateTime Date 
       {
           get 
           {
               return date;
           }
           set 
           {
                if (value.Year > 1900 && value.Year <= DateTime.Today.Year)
               {
                   date = value;
               }
               else
                   throw new ArgumentOutOfRangeException();
           }

       }

Differences between Value & Reference type in C#

Value TypeReference Type
Variables of value type directly contain their dataVariables of reference type store references to their data
Each variable has its own copy of dataTwo variables can refer the same object
Allocated on stackAllocated on heap
Dealloced when the stack unwinds or when their containing type get deallocated. Therefore, allocations and deallocations of value types are in general cheaper than allocations and deallocation of reference typeDeallocated through garbage collection
Value type arrays are allocated inline, meaning that the array elements are the actual instances of the value typeArrays of reference types are allocated out-of-line, meaning the array elements are just references to instances of the reference type residing on the heap. Therefore, allocations and deallocations of value type arrays are much cheaper than allocations and deallocations of reference type arrays
Value types get boxed when cast to a reference type or one of the interfaces they implement. They get unboxed when cast back to the value typeno such boxing occurs as reference types are cast
reference type assignments copy the reference, whereas value type assignments copy the entire value. Therefore, assignments of large reference types are cheap
er than assignments of large value types




reference type assignments copy the reference, whereas value type assignments copy the entire value. Therefore, assignments of large reference types are cheaper than assignments of large value types

Structs

Structs are like classes but they are value types. Use structs instead of classes when the instances are small and short lived and will not have to be boxed frequently.