Jagged Array

What is Jagged Array?

Jagged array is called as "array of arrays". when you need a data inside your array element at that time you can use Jagged array.

How to declare Jagged Array?

You can declare Jagged array by following way, you can use any option by your choice.

1. int[][] jaggedArray=new int[3][]

2.int[][] jaggedArray=new int[3][]{
 
        new int[2]{1,2},
        new int[3]{1,2,3}
};

Let's see below example:

 static void Main(string[] args)
        {
            try
            {
                int[][] jaggedArray = new int[3][];

                //The element of JaggedArray must be defined. here we define size of 2.
                jaggedArray[0] = new int[2];
                jaggedArray[1] = new int[2];
                jaggedArray[2] = new int[2];

                //Set values in jaggedArray
                jaggedArray[0][0] = 1;
                jaggedArray[0][1] = 2;
                jaggedArray[1][0] = 3;
                jaggedArray[1][1] = 4;
                jaggedArray[2][0] = 5;
                jaggedArray[2][1] = 6;
                
                for(int i = 0; i < jaggedArray.Length; i++)
                {
                    for (int k = 0; k < 2; k++)
                    {
                        Console.WriteLine(jaggedArray[i][k]);
                    }
                }
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

Output:
1
2
3
4
5
6

C# Interview Questions and answer


1.Can we declare multiple catch blocks to be execute?

Ans:No,Multiple catch blocks can't be execute  Once the proper catch code executed, the control is transferred to the finally block, and then the code that follows the finally block gets executed.


2.What is Constructor?
Ans:A constructor is a member function in a class that has the same name as its class. The constructor is automatically invoked whenever an object class is created. It constructs the values of data members while initializing the class.

3.Explain Jagged array
Ans:The Array which has elements of type array is called jagged Array. The elements can be of different dimensions and sizes. We can also call jagged Array as an Array of arrays.

4.What is ref and Out Parameter in c#?
Ans:Both are used to pass value as a reference.An argument passed as ref must be initialized before passing to the method whereas out parameter needs not to be initialized before passing to a method.

5.What is Serialization?
Ans:When we want to transport an object through a network, then we have to convert the object into a stream of bytes. The process of converting an object into a stream of bytes is called Serialization. For an object to be serializable, it should implement ISerialize Interface. De-serialization is the reverse process of creating an object from a stream of bytes.

6.Can we use This command with Static method?
Ans:We can't use 'This' in a static method because we can only use static variables/methods in a static method.

7.Give difference between const and read only.
Ans:Constant variables are declared and initialized at compile time. The value can't be changed afterward. Read-only is used only when we want to assign the value at run time.

8.What is an Interface?
Ans:An Interface is an abstract class which has only public abstract methods, and the methods only have the declaration and not the definition. These abstract methods must be implemented in the inherited classes.

9.What is Sealed class?
Ans:We create sealed classes when we want to restrict the class to be inherited. Sealed modifier used to prevent derivation from a class. If we forcefully specify a sealed class as base class, then a compile-time error occurs.

10.What is Method Overloading?
Ans:Method overloading is creating multiple methods with the same name with unique signatures in the same class. When we compile, the compiler uses overload resolution to determine the specific method to be invoke.

11.What is Difference between Array and Array List?
Ans:In an array, we can have items of the same type only. The size of the array is fixed when compared. To an arraylist is similar to an array, but it doesn't have a fixed size.

12.What is Difference between Interface ans Abstract class?
Ans.Interfaces have all the methods having only declaration but no definition. In an abstract class, we can have some concrete methods. In an interface class, all the methods are public. An abstract class may have private methods.

13.What is Delegate?
Ans:Delegates are same are function pointers in C++, but the only difference is that they are type safe, unlike function pointers. Delegates are required because they can be used to write much more generic type-safe functions.

14.Difference between Method Overloading and Method Overriding?
Ans:In method overriding, we change the method definition in the derived class that changes the method behavior. Method overloading is creating a method with the same name within the same class having different signatures.

15.What is Difference between struct and class?
Ans:Structs are value-type variables, and classes are reference types. Structs stored on the Stack causes additional overhead but faster retrieval. Structs cannot be inherited.





Ref and Out

What is Ref and Out Keyword?

Ref and out keywords in C# are used to pass arguments within a method or function. Both indicate that an argument/parameter is passed by reference.

Ref

The ref keyword is used to pass an argument as a reference. This means that when value of that parameter is changed in the method, it gets reflected in the calling method. An argument that is passed using a ref keyword must be initialized in the calling method before it is passed to the called method.

Out

The out keyword is also used to pass an argument like ref keyword, but the argument can be passed without assigning any value to it. An argument that is passed using an out keyword must be initialized in the called method before it returns back to calling method.


Please find below example for more clarity.I have used both ref and out parameter and also describe how it's work. you can also find different between ref and out comparing codes.


  class Proram
    {
        public static void Main() //Calling Method
        {
            int refval=0;//Must be define value
            int outval; //No need to define value

            GetNumberByRef(ref refval);
            Console.WriteLine("Values after called method using ref is {0} ", refval);

            GetNumberByOut(out outval);
            Console.WriteLine("Value after called method using our is {0} ", outval);

            Console.ReadLine();
        }
        public static void GetNumberByRef(ref int value)//Called Method
        {
            value = 101;//here it's optional to define value
        }
        public static void GetNumberByOut(out int value)//Called Mathod
        {
            value = 101;//You must define value here
           
        }
    }

Output
 
Values after called method using ref  is 101
Value after called method using our is  101


Note: Out and ref cannot be used in method with async mathod.

Async await in c#

What is async await in c#?


You might have already heard about asynchronous programming, either in C# or in some other language. In this page I will try to explain it to you, how to understand the concept easily, why and when we write asynchronous, the structure of async / await.

Asynchronous programming is very helpful in this condition. By using Asynchronous programming, the Application can continue with the other work that does not depend on the completion of the whole task.if any task depends on another task then next task will not execute until first task not completed.

Async and await are the code markers, which marks code positions from where the control should resume after a task completes.

We will get all the benefits of traditional Asynchronous programming with much less effort by the help of async and await keywords.

Let's take example so understand it properly

class Proram
    {
        public static void Main()
        {
       
            ProcessOne();
            IndependentProcess();//this process will run separately
            Console.ReadLine();
        }
        public async static void ProcessOne()
        {
            /*
             You can see that we mark DependedProcess method as await
             means untill DependedProcess will not complete next line will not called
            */
            await Task.Run(new Action(DependedProcess));
            Console.WriteLine("Process One Called");
        }
     
        public static void DependedProcess()
        {
            Thread.Sleep(2000);
            Console.WriteLine("Process Two Called");
        }
        public static void IndependentProcess()
        {
            Console.WriteLine("Independent Process");
        }
    }

Output:
Independent Process
Process Two Called
Process One Called

Summary: In above program you can see that Once DependentProcess method complete process after that next line of code will execute.while Independentprocess method will run separately this is called the Asynchronous programming.



















Operator Overloading

What is Operator overloading?

Opearator overloading is a concept which is related to polymorphisam. Overloaded operators are functions with special names the keyword operator followed by the symbol for the operator being defined.

Operator overloading gives the ability to use the same operator to do various operations

Overloaded operators are functions with special names the keyword operator followed by the symbol for the operator being defined. similar to any other function, an overloaded operator has a return type and a parameter list.

Let's try to understand  Operator overloading (+)  by below example. using the + Operator you can do addition of two values and also contact two strings as below

 Obj 1 Operator     Obj 2 Result
 "C#"+ "Tutorial" C# Tutorial  
 15   +     20 35
Obj1       +    Obj2  can we do like that?? (let's do that with Operator Overloading) 


Please see below example for operator overloading and get to know that how we do addition of Obj1 + Obj2. run it on your machine to get more clerify.

    class Proram
    {
        public static void Main()
        {
            Course obj1 = new Course();
            obj1.Name = "C#";
            obj1.TotalMarks = 200;

            Course obj2 = new Course();
            obj2.Name = "Programming";
            obj2.TotalMarks = 300;

            Course obj3 = new Course();
            obj3 = obj1 + obj2;//Here operator overloading called.

            Console.WriteLine(obj3.Name + " - " + obj3.TotalMarks);
            Console.ReadLine();
        }
    }
    class Course
    {
        public string Name = "";
        public int TotalMarks = 0;

        public static Course operator +(Course Obj1, Course Obj2)
        {
            Course Obj3 = new Course();
            Obj3.Name = Obj1.Name + Obj2.Name;
            Obj3.TotalMarks = Obj1.TotalMarks + Obj2.TotalMarks;
            return Obj3;
        }
    }

Output
C#Programming - 500




Please visit given link for more details on Operator overloadig 

Sorted List - Generic

C# Sorted List

In c#, SortedList is a generic type of collection and it is used to store a collection of key/value pairs that are sorted by key based on the associated IComparer<T> implementation.

By default, the sortedlist will sort a key/value pairs in ascending order of the key and the sortedlist will allow storing only the strongly-typed objects i.e. the key/value pairs of the specified data type.

In c#, the sortedlist will allow us to store duplicate values but the keys must be unique and cannot be null to identify the values in sortedlist and the size of sortedlist will vary dynamically so you can add or remove elements from the sortedlist based on our application requirements.

C# includes two type of SortedList, generic SortedList and non-generic SortedList. Generic SortedList denotes with angel bracket: SortedList<TKey,TValue> where TKey is for type of key and TValue is for type of value. Non-generic type do not specify the type of key and values.


You can instantiate SortedList<TKey, TValue> by specifying type for key and value, as shown below.

Ex. SortedList<TKey, TValue> slist = new SortedList<TKey, TValue>();


Properties


 Property     Description
 Capacity     Gets or sets the number of elements that the SortedList<TKey,TValue> can store 
 Count Gets the total number of elements exists in the SortedList<TKey,TValue>.
 IsReadOnly Returns a boolean indicating whether the SortedList<TKey,TValue> is read-only.
 Item Gets or sets the element with the specified key in the SortedList<TKey,TValue>.
 Keys Get list of keys of SortedList<TKey,TValue>
 Values Get list of values in SortedList<TKey,TValue>.


Method

 Method         Description
Add  Add key-value pairs into SortedList<TKey, TValue>.
Remove Removes element with the specified key.
Remove At Removes element at the specified index.
Contains Key Checks whether the specified key exists in SortedList<TKey, TValue>.
Contains Value Checks whether the specified key exists in SortedList<TKey, TValue>.
Clear Removes all the elements from SortedList<TKey, TValue>.
Index Of Key Returns an index of specified key stored in internal array of SortedList<TKey, TValue>
Index Of Value
 Returns an index of specified value stored in internal array of SortedList<TKey,   TValue>
Try Get Value Returns true and assigns the value with specified key, if key does not exists then return false.


Example

 class CollectionExamples
    {
        public static void Main(String[] args)
        {

            SortedList<int, string> sl = new SortedList<int, string>();
            sl.Add(3, "Three");
            sl.Add(1, "One");
            sl.Add(2, "Two");
            sl.Add(4, null);

            foreach (var item in sl.Keys)
            {
                Console.WriteLine("Sorted List {0}", item);
            }
            Console.ReadLine();

        }
    }


Dictionary

C# Dictionary


  • The Dictionary<TKey, TValue> class is a generic collection class in the System.Collection.Generics namespace. TKey denotes the type of key and TValue is the type of TValue.
  • There is a non-generic collection called a Hashtable, which does the same thing, except that it operates on type object. However, you want to avoid the non-generic collections and use their generic counterparts instead
  • Dictionary cannot include duplicate or null keys, where as values can be duplicated or set as null. Keys must be unique otherwise it will throw a runtime exception.
  • The capacity of a Dictionary is the number of elements that Dictionary can hold.


Properties

 Property

 Description

 Count             Gets the total number of elements exists in the Dictionary<TKey,TValue>              .
 IsReadOnly Returns a boolean indicating whether the Dictionary<TKey,TValue> is read-only.
 Item Gets or sets the element with the specified key in the Dictionary<TKey,TValue>.
 Keys Returns collection of keys of Dictionary<TKey,TValue>.
 Values Returns collection of values in Dictionary<TKey,TValue>.

Methods


 Method     Description
 Add                Add key-value pairs in Dictionary<TKey, TValue> collection.                                                                  
 Remove     Removes the first occurrence of specified item from the Dictionary<TKey, TValue>.
 ContainsKey  Checks whether the specified key exists in Dictionary<TKey, TValue>.
 ContainsValue Checks whether the specified key exists in Dictionary<TKey, TValue>.
 Clear Removes all the elements from Dictionary<TKey, TValue>.
 TryGetValue Returns true and assigns the value with specified key, if key does not exists then return false.


Example

 public static void Main(String[] args)
   {
           
            Dictionary<int, string> _dictionary =  new Dictionary<int, string>();

            // Adding key/value pairs  
            _dictionary.Add(1, "Hello");
            _dictionary.Add(2, "This is");
            _dictionary.Add(3, "Blog for C#");

            _dictionary.Remove(1); //Remove value which key is 1

            Console.WriteLine("Is Key Exist?: {0}",_dictionary.ContainsKey(2));//Return True
            Console.WriteLine("Is Value Exist?: {0}", _dictionary.ContainsValue("This is"));//Return True
            foreach (KeyValuePair<int, string> ele1 in _dictionary)
            {
                Console.WriteLine("{0} and {1}",
                          ele1.Key, ele1.Value);
            }
            Console.ReadLine();

           
    }

Jagged Array

What is Jagged Array? Jagged array is called as "array of arrays". when you need a data inside your array element at that time you...