C# interview questions and answers-part1


1)Declaring arrays in C#?

Please observe there difference between array declaration from other languages

Single Dimension Arrays:
Declaration:
int[ ] myArray;
myArray = new int[10];
Initialization:
int[ ] myArray = new int[10] {1,2,3,4,5,1,2,3,4,5};

Multi Dimension Arrays:


string[ , ] myArray ;
myArray = ne string[ 4 , 4 ];

if we want we can declare three dimension array also
string[ ,  , ] myArray ;
myArray = ne string[4,4,4];

2)Can we declare property as abstract in C#?
 (or)
Can we override the properties in C# ?

Yes.

3)How can we declare read only property?

If the property having only get; . Then we called that property as read-only property.
By default all Abstract properties are read-only properties.

4)Can we create Array with objects?

Yes we can but all the objects must be derived from single base class.

ex:
public class Program1 : Program

    {
   }
public class Program2 : Program

    {
   }

public class Program3 : Program

    {
   }
Program[]  objArr = new Program{ new Program1(),new Program2() ,new Program3() };

5)What is difference between IEnumerable and IEnumerator in C#?

Both belongs to System. Collections
IEnumerable Exposes the enumerator 
IEnumerable is the base interface for all non-generic collections
Its contain one method called GetEnumerator() which returns an IEnumerator.
Which means IEnumerable using IEnumerator.
IEnumerator supports iteration over non-generic collections

6)Can we declare default constructor in Structures in C#?

No
Structure members can not have initializers.

7)Explain about delagates in C#? 

-it is reference type which represents method.

   -delegate object can contain reference of method


    -with the help of delegate object we can invoke a method dynamically based on its reference.


-delegates are object-oriented, type safe  and secure.


Delegate declaration:


Delegate declaration similar to the method declaration except delegate keyword and  we need to have 


same arguments and return type.


8)Example on delegates calling Static and Instance methods?


OR


How can we call static methods using delegates?


OR


How can we call Instance methods using delegates?


OR


How to call more than one method at a time?


class MyClassForDelegates


    {

        public static void One(string s)
        {
            Console.WriteLine("  One, {0}!", s);
        }

        public static void Two(string s)

        {
            Console.WriteLine("  Two, {0}!", s);
        }

        public void Display()

        {
            Console.WriteLine(" hi i am from Instance method");
        }

        public static void Main()

        {
            StaticMethodDelegate a,b,f;

            InstanceMethodDelegate e;


            a = new StaticMethodDelegate(One); // Calling static method 


            b = new StaticMethodDelegate(Two);
           

            MyClassForDelegates myObject = new MyClassForDelegates();


            Console.WriteLine("Invoking delegate One:");

            a("A");


            Console.WriteLine("Invoking delegate Two:");


            b("B");


            f = a + b;


           Console.WriteLine("Invoking delegate f:");


            f("add");


            e = myObject.Display;


            e.Invoke(); // Calling instance method 


            Console.ReadLine();

        }

    }  


}


output:


Invoking delegate One:

  One, A!


Invoking delegate Two:


  Two, B!


Invoking delegate f:


  One, add!


  Two, add!


 hi i am from Instance method 


9)Conditional Methods in C#?

Its define mechnism for controlling the method execution i.e either inclde or omitted from compilation.

For this we need to use System.Diagnostics; 


public class Program 
    {
       [Conditional("DEBUG")]
       void Info()
       {
           Console.WriteLine("I am from Conditional");
       }
        static void Main(string[] args)
        {
            Program pObj = new Program();
            pObj.Info();
            Console.ReadLine(); 
        }
    }

10) What is init only properties  C#.NET ?

Properties which are initialized through the constructor is called  init only properties.

11) What is DTO (Data transferred Object) C#.NET?

It is a subset of model.

There are several reasons behind implementing DTO, Main reason is security.

public class Student
{
public string RNo {get; set;}
public string SNama {get; set;}
public int Fee {get; set;}
}


public class StudentDTo
{
public string RNo {get; set;}
public string SNama {get; set;}
}

In DTO model Fee property  not available.

Output:

I am from Conditional

if you compile above program in Release mode. Its wont show any out put because of Conditional attribute.

12)What is using static directive in C#.NET?

This feature was added in C# version 6.0

uisng static directive , we can use static member in program directly without importing static class

using System;

using static System.Console;

namespace CSharp_Shell
{
public class proj
{
   private protected string myval="shiva";
}
    public class Program
    {
        public static void Main() 
        {
        WriteLine("from static imports");
       ReadLine();
      
        }
    }
}

Output

from static imports

13)What is when keyword in C#.NET?

-This feature was added in C# version 6.0
-when keyword is used to specify filter condition based on filter condition evaltion respective block of code will be executing. 
-when key word used in try-catch , switch statemen , switch expression 
 
using System;

using static System.Console;

namespace CSharp_Shell
{
public class proj
{
   private protected string myval="shiva";
}
    public class Program
    {
      public static void Main() 
        {
       try
       {
        WriteLine("from static imports");
       ReadLine();
       }
      catch(Exception e) when (e.Message.Trim.Equals("xyz"))
      {
     
      }
        }
    }
}

14) What expression bodied members in C#.NET ?

-This feature was added in C# version 6.0
-using Expression body definitions you can specify member defination in easy and understandable way
-return type of expression implicitly convertable to member return  type

public override string ToString( ) => $"{FirstName}{LastName}".Trim();

15) What => operator in C#.NET?

=> operator used in two places one is in lambda expressions , another is in expression bodied members

16) What is null propagator (or ) Null-conditional operators ?. and ?[] in C#.NET? 

-This feature was added in C# version 6.0
-Sometimes exception in program not allowing to execute other lines of code, Using this operator we avoid null related exception 
-This operator applies at member level (property) and element level (arrays , indexers )
-If b value is null, the result of b?.x or b?[x] is null.
-If b  is non-null, the result of b?.x or b?[x] is having some value 

strTest.ElementAt(1); //May get the exception if strTest is null
Console.WriteLine(strTest?.ElementAt(1)); //if strTest is null also not breaking program excution

17) What is string interpolation in C#.NET?

-This feature was added in C# version 6.0 -Using $ character identify the string interpolation -Using this featuer write readable , formatable strings very easily

public override string ToString( ) => $"{FirstName}{LastName}".Trim();

18)What is out variables in C#.NET?
 
out variable mainly inteded for carrying output. you can pass out variable as a arguement in method call so that need not to declare out variable sepharatley 
 Sum(2,3, out int result); 
 Console.WriteLine(result); // o/p : 5

19)What is Tuples in C#.NET?

-Tuples are lightweight data structures.
-Tuples are used to group multiple data elements.
-Can not implement own methods in Tuples but you can built in methods.
-If you want to return more than one value form method you can use this Tuples
-Currently tuples supporting  == , != operators

(int, int) tup1 = (4, 5);
Console.WriteLine($"Tuple with elements {tup1.Item1} and {tup1.Item2} sum is {tup1.Item1+tup1.Item2}");

o/p : Tuple with elements 4 and 5 sum is 9

20) What is discards in C#.NET? 

-Discards are write only variables whose value not ontended to use program
-Discards represented with '_'
-Discards used to represent the tuples deconstructed values and method with output parameters values


For Part2  click here




No comments:

Post a Comment