Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Tuesday, August 12, 2014

Static Class

  1. Cannot derive from Static Class
  2. Cannot create instance of Static class using new keyword
  3. Static class can be public or internal
  4. Static class can NOT be private or protected or protected internal
  5. Static class can NOT have non-static members

1) 
static class ThisClassIsStatic
{
    static string comment;
    static int count = 0;
}
class ThisIsDervied : ThisClassIsStatic   //NOT POSSIBLE
{
}

2)
ThisClassIsStatic obj = new ThisClassIsStatic(); //NOT POSSIBLE

3) 
public static class ThisClassIsStatic  //POSSIBLE
{
}

4)
private static class ThisClassIsStatic  //NOT POSSIBLE

5)
    static class ThisClassIsStatic
    {
        static string comment;
        static int count = 0;
        int index = 0; //NOT POSSIBLE

    }

C# Base

    class Program
    {
        static void Main(string[] args)
        {
            B b = new B();
            Console.Read();
        }
    }

    class A
    {
        internal int x = 10;
        public int MyProperty { get; set; }
        public A()
        {          
            Console.WriteLine("A Constructor");
        }
    }

    class B:A
    {
        public B(): base()
        {                
            Console.WriteLine("B Constructor ");
        }
    }

What's the output of the above program?

Note: base keyword can be used ONLY from derived class's constructor to access base class members (non-private members)

Saturday, August 9, 2014

C# Extension Method - Sample

class Program
{
    static void Main(string[] args)
    {
        string s = "hello please tell me the word count";
        Console.Write(s.WordCount());
        Console.Read();
    }
}

public static class StringExtension
{
    public static int WordCount(this string value)
    {
        return value.Split(' ').Length;
    }
}

Wednesday, May 7, 2014

Is C# a 100% Object Oriented Programming Language?

C# is NOT a pure object oriented programming language. 

Object oriented language should support:
  1. Encapsulation
  2. Polymorphism
  3. Inheritance
  4. All predefined type are objects
  5. All operations performed by sending messages to objects
  6. All user-defined types are objects
C# does not support point#4 & 5. 

In C#, predefined type can be struct. Example: integer > public struct Int32

So C# does not qualify as pure object oriented language.




Reference:

Tuesday, September 11, 2012

Datastructures in .NET


a.       Stack:
·   FILO (first in last out)
·   Push(object o) – insert an object at top of stack
·   POP() – removes object at top of stack
·   Peek() – returns object at top of stack without removing
·   One of the classic examples of stack in .net framework is in memory management of value types.
·   There are non generic collection stack object (System.Collections.Stack) and generic collection stack object (System.Collections.Generic.Stack)



b.      Queue:
·   FIFO
·   Enqueue(object o) – add an object at end of queue
·   Dequeue() – remove object at beginning of queue
·   Peek() - return object at beginning of queue
·   First object entering to the Queue, exits first
·   One of the classic example of queue implementation in MSMQ
·   Queue is used in the highly reliable communication scenarios. Even if the message channel not available, messages are stored in the queue and transmitted once the channel is up.
·   There are non generic collection object (System.Collections.Queue) and generic collection object (System.Collections.Generic. Queue)


c.       Hashtable           
·   Hashtable stores key – value pair
·   Is organized based on the hash code of the key
·   Each element in hashtable is stored as DictionaryEntry object
·   A key cannot be null, but value can be
·   It is a non generic collection System.Collections type
·   Hashtable stores types of object
·   There is a type conversion required every time when we use hashtable

IDictionary, ICollection, IEnumerable, ISerializable, IDeserializationCallback, ICloneable

d.      Dictionary
·   Dictionary is similar to Hashtable (key-value pair storage)
·   It is a generic collection (System.Collections.Generics)
·   Type of the object to store in the dictionary should specify at compile time
·   Performance wise,  Dictionary is better option that Hashtable
IDictionary, ICollection<KeyValuePair>, IEnumerable<KeyValuePair>, IDictionary, ICollection, IEnumerable, ISerializable, IDeserializationCallback

e.      List
·   It is generics collection (System.Collections. Generics)
·   It represents strongly typed list of objects
·   Consider a scenario to store all the employee names of Satyam, then use List
·   No type conversion required hence preferred over ArrayList

IList, ICollection, IEnumerable, IList, ICollection, IEnumerable

f.        ArrayList
·   ArrayList is a non generic collection (System.Collections)
·   Size can be dynamically increase
·   ArrayList stores objects
·   Type conversion required every time when use AL
·  This affects the performance

Monday, September 10, 2012

Struct in C#.NET

            //NOTES: STRUCT

            // - struct is a value type 
            // - no need to use new keyword
            // - cannot inherit from struct(error: cannot derive from sealed type)
            // - struct allows properties/method which uses reference type.



namespace StructSample
{
    class Program
    {
        static void Main(string[] args)
        {
            Point p;
            p.x = 10;
            p.y = 20;

            p.name = "wgi";

            Console.WriteLine(p.Add());

            Console.Read();
        }
    }


    struct Point
    {
        public int x, y;

        public string name;

        public int Add() { return x + y; }
    }


    //class newPoint : Point
    //{
    //}
}

Monday, April 16, 2012

Advantage of abstract class over interface

Advantage of abstract class over interface:

Consider versioning:

·         You cannot add members to interface without breaking the existing code.  
·         But you can safely add new members to abstract classes.



Choosing between interface & abstract class:

·         Use interface when you want to implement multiple inheritance.
·         Use interface for decoupling
·         Use abstract class in case of frequent versioning scenario.

Compare 2 generic list

How to Compare 2 generic lists:

            List<int> list1 = new List<int> { 1, 2, 3, 5, 6 };
            List<int> list2= new List<int> { 1, 2, 3 };


Answer: if you are trying to see if 2 sets are equal, then the best approach is to check the except extension method on Enumerable class. And make sure that the result does not have any entries.


            var except = Enumerable.Except(list1, list2);

            if (except.Count() > 0)
                Console.Write("Not equal");
            else
                Console.Write("equal");;

Reference:

Tuesday, February 28, 2012

Multithreading in C# - Basics

·         Multithreading – is the parallel execution of code
·         Use of multithreading
1. Maintaining a responsive UI
2. Allow requests to process simultaneously

·         Join –wait for the thread to end/complete the execution
·         Sleep – pauses the current thread for specified period
·         IsAlive – property returns true if thread is alive

Note: Thread will be in blocked state while waiting on a join/sleep. And will not consume resources

·         Yeild – pauses thread running on same processor.
·         Preempted – a thread is said to be preempted when its execution is interrupted due to external factor
·         Interrupt and abort – interrupt will wait for until thread block to complete, while abort breaks where it is executing

·         Thread scheduler manages multithreading
1. It’s a function typically CLR delegates to Operating System
2. TS ensures all active threads are allocated appropriate execution time
3. And threads are waiting/blocked do not consume CPU resource
4. On  a Single processor system, TS perform time-slicing
5. On a multi processor system, TS perform mixture of time slicing and concurrency

·         Process Vs Thread – a thread in execution is a process. Threads run parallel within a single process. Processes are fully isolated from each other, where threads are partially isolated from each other. (threads share heap memory with other threads)

·         Foreground and background threads – by default foreground threads are created. (Thread.IsBackground=true)

·         Thread Priority – property determines how much execution time it gets (Lowest, BelowNormal, Normal, AboveNormal, Highest)

·         Thread pooling –allow execution of the threads simultaneously.   Once the limit is reached it queues up and continues execution when other finishes (ThreadPool.QueueUserWorkItem)

·         Asynchronous delegate – If a thread wants to notify (return value back) after it has finished execution, then this can be achieved using asynchronous delegate.

1. Create a delegate for the method to be called (Func delegate)
2. Call BeginInvoke on delegate with IAsyncResult return value
Note: BeginInvoke return immediately to the caller.

·         ThreadState: gives you threads execution status.
o   Unstarted
o   Running
o   WaitSleepJoin
o   Stopped

·         Thread synchronization
o   Lock (Monitor.Enter, Monitor.Exit)
o   Mutex
o   Semaphore
o   SemaphoreSlim
o   SpinLock

·         Lock – ensure only one thread can enter particular section of code at a time (Exclusive lock)
object locker = new object();
                 System.Threading.Monitor.Enter(locker);

           
                 System.Threading.Monitor.Exit(locker);
·         Mutex – is an exclusive lock. Purpose is inter-process synchronization. It can work across multiple processes. Mutex can be computer-wide or application-wide.

·         Semaphore – Ensures not more than a specified number of concurrent threads can access a resource. It is cross process. 


Thursday, February 16, 2012

How to create your own generic list?

How to create your own generic list?

1.       Declare class with type parameter T (Eg: SatyamList<T> )
2.       Implement IList<T>, ICollection<T>, IEnumerable<T> interfaces in the class
3.       Create a private ArrayList object within class for storing the custom list values
4.       Write the implementations for the interfaces (in step2)








Friday, December 3, 2010

default access modifier in c#

internal


 public
The type or member can be accessed by any other code in the same assembly or another assembly that references it.
private
The type or member can be accessed only by code in the same class or struct.
protected
The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class.
internal
The type or member can be accessed by any code in the same assembly, but not from another assembly.
protected internal
The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly. Access from another assembly must take place within a class declaration that derives from the class in which the protected internal element is declared, and it must take place through an instance of the derived class type.

Reference:
http://msdn.microsoft.com/en-us/library/ms173121.aspx

Tuesday, November 30, 2010

yeild

yeild is the income return of an investment. (in finance)

in C#,

  • yeild keyword use inside iterator block.
  • it indicates the end of iterator block

restriction
  • cannot use with unsafe block
  • parameter to method cannot be out/ref 
  • cannot appear in anonymous method

Monday, November 22, 2010

upcasting and downcasting

upcasting - is possible, its implicit coversion and is safe. (ie,  A aa=new B() - is upcasting. Here were are converting from Type B to Type A. It is possible, because A is the base class. And all the base class methods and properties will be available in object aa). Its called upcasting because we more moving up the object hierarchy.

downcasting - is explicit conversion and is unsafe. you will have to be very careful while downcasting types.  Its called downcasting because we are moving down the object hierarchy.


(with sample: class A, class A:B, class C:B)

Class A
{
}

Class B:A
{
}

Class C:B
{
}


Question:
A aa=new B();       // is this possible? Ans:
A aa=new C();       // is this possible? Ans:
B bb=new A();       // is this possible? Ans:
B bb=(B)new A();  // is this possible? Ans:


Solution

A aa = new B(); // is possible.

Implicit conversion from Type B to Type A is possible. Because Type A is the base class and Type B is derived from Type A.

//B bb = new A();   //compile Error : Cannot implicitly convert type 'A' to 'B'. An explicit conversion exists


//B bb = (B) new A(); //runtime Error : System.InvalidCastException - Unable to cast object of type 'A' to type 'B'



Hint:

Car c=new BMW();   //possible
BMW b=new Car();  //not possible, compile error - implicit conversion not possible from type Car to BMW
BMW_E_Series be=new Car(); //not possible, compile error
BMW_E_Series be= (BMW_E_Series) new Car(); //runtime error, explicit conversion not possible


Reference:

http://www.c-sharpcorner.com/UploadFile/pcurnow/polymorphcasting06222007131659PM/polymorphcasting.aspx

Tuesday, November 16, 2010

Difference between new Operator and Modifier

• new operator Used to create objects on the heap and invoke constructors.

• new modifier Used to hide an inherited member from a base class member.

Example for new modifier:


Tuesday, November 9, 2010

Nested class

namespace NestedClass
{
class Program
{
static void Main(string[] args)
{
A a = new A();

A.AA aa = new A.AA();

}
}

public class A
{
public class AA
{
public int i = 10;
A x = new A();
A.AA xx = new AA();
}
}
}

String is a reference type. In the below code, what would be the output?

class Program
{
static void Main(string[] args)
{
string s = "abc";
CallMethod(s);
Console.WriteLine(s);
Console.Read();

}
static void CallMethod(string s)
{
s = "xyz";
}
}

Output: abc

Wednesday, December 2, 2009

Sealed

  • It restricts inheritance
  • Cannot derive from Sealed type
 

    Wednesday, November 25, 2009

    C# constructors

    1. Static constructor
    2. Instance constructor (non-static constructor)



    Static constructor
    • Does not take access modifiers
    • Cannot access any non static members
    • Static constructor will get called as soon as we create an instance of the class or we refer the class
    • class which implements static constructor does not has to be static.
    • static constructor calls only once.
    • it can be used for initializing objects
      eg, say there is an employee class, and we want to know how many employee object's are created. This case you can create a static integer variable and increment the count.



    

    Tuesday, November 24, 2009

    C# 3.0 features

    1. 3.0 allows properties without local variables
    2. var  (varient) - it is implicitly typed variable
    3. Anonymous variable
    4. Lamda expression
    5. FUNC<>
    6. Extention Method

    Here is the detail:

    1. C#3.0 allows properties without local variables: 
    Tip: Type prop in the visual studio and press tab
     2.  Simple and implicitly typed local variable

    • It is implicitly typed variable
    • var i=10;
    • var str="nidhish";
    • var x="109"; // It is invalid. Compiler does not allow this.
    • var CANNOT be used as a parameter or a return type. It is heavily used in LINQ
    3. Anonymous variable:

    • it is helpful for object initialization
    • Example:
    List mystring=new List {
      "Item1",
      "Item2",
      "Item3"}
    4. Lamda expression:

    • Example:
    delegate long myadd(int n1,int n2);
    Public void TestLamda()
    {
       myadd ad= (n1,n2) => { return n1+n2; };
       Console.WriteLine(ad.invoke(100,150));
    }

    5. Extending type with extension method

    Extension method provide developers to extend the functionality of an existing type. Extension methods are static methods with keywork this

    Eg: Extend string class with a reverse method

      Saturday, November 21, 2009

      Order of execution of Catch statements

      • System.Exception is the base class for Exceptions
      • System.Exception should be the last catch block.
      • Catch block for all the child exceptions should be declared before System.Exception. Compiler throws exception if the order is not following.

      •  Sample (WRONG)

                  try
                  {
                      int c= 10/0;
                  }
                  catch (Exception ex)
                  {
                      Console.WriteLine("Exception block:" + ex.Message);
                  }
                  catch (DivideByZeroException dex)
                  {
                      Console.WriteLine("DivideByZeroException block:" + dex.Message);
                  }
      COMPILE ERROR: A previous catch clause already catches all exceptions of this or of a super type ('System.Exception')

      • Sample (CORRECT)
                   try
                  {
                      int c= 10/0;
                  }
                  catch (DivideByZeroException dex)
                  {
                      Console.WriteLine("DivideByZeroException block:" + dex.Message);
                  }
                  catch (Exception ex)
                  {
                      Console.WriteLine("Exception block:" + ex.Message);
                  }


      Eg : Another Sample