C# interview questions and answers-part2

1)What is Pattern matching in C#.NET? 

Pattren matching consisting set of features that enables to new ways of control flow. 

For example is and switch expressions etc 

Object o = new Student("Jane");

ShowName(o);

public static void ShowName(object o)
{
      if (o is Student s) 
     {
         Console.WriteLine(s.Name);
      }    
}

2)What is Local functions in C#.NET?

-If your function called only once , then declare function inside the context of another function.
-Local functions enables  easy debugging and increase performance.

3)What is Async main in C#.NET?

-This feature was added in C# version 7.0
-Using Async main method you can use await in your main method.

static async Task Main()
{
    await TestAsyncMethod();
}

4)What is default operator in C#.NET?

-Using default operator you can get default value of type

Example : 
Console.WriteLine(default(int));  // o/p: 0
Console.WriteLine(default(object) is null);  // o/p: True

5)What is Default literal in C#.NET?

-Using default literal to generate default of type when compiler compile the expression.
-Use default literal in assignment or inatilization of variable.
-Use default literal In a method call, to provide default value
-Use default literal For optional parameters default values 

Func<string, int> testClause = default(Func<string, int>);
Now you can omit right hand side rewrite the above 
Func<string, int> testClause = default;


6)What is buffer overrun or buffer overflow in C#.NET?

-When user intentenally enter the more and more data then system store this data different memory locations so that this caused to diffrent behaviour of the program this is called buffer overflow.
-To avoid above issue before assigning the value needs to check the size of user entered data.

if(output.length >= 255)
{
result = output;
}

7)What is stray pointers in C#.NET?

-Should not to use the pointers after you have called delete on it because the pointer still points to the old area of memory so that the compiler is capable to put other data there if your again using the deleted pointer.
-When we call delete on the pointers just set pointer to the null otherwise will get strange behavior this is called stray pointers.

8) What is Named and Positional arguments in C#.NET? 
(or )
What is Named and Positional parameters in C#.NET?

-C# version 4.0 introduce the Named parameters.
-By using Named argument enables you to matching the argument by it Name not by its position. 
-By using named arguments can avoid the ambiguity while passing the parameters, you can pass in any order.

DisplayDetails("Shiva", 123 , "Gummadidala"); // Normal method call with positional arguments

DisplayDetails(name:"Shiva", rollNumber:123,fatherName:"Gummadidala"); 
//method call with named parameter

public void Display(string name , int rollNumber, string fatherName)
{
//Method defination here
}
you can mix position positional and named arguments but ordering is very important. 

DisplayDetails(123, name:"Shiva", fatherName:"Gummadidala");  //Invalid and out of order 

9)What is Optional Arguments in C#.NET?

-Sometimes may not to pass arguments to all the parameters, Achieving this  behavior using optional Arguements.
- Separate keyword not required for this just needs to give default value in method definition parameter. 
-If value is passed considered that values , if not considered default value as parameter value.
-One thing needs keep in mind is "calling method provides an argument for any one of a succession of optional parameters, it must provide arguments for all preceding optional parameters" if not its showing error"

public void DisplayDetails(string name , int rollNumber, string fatherName , int Age = 60); 
//Above method Age is an optional parameter

10)Why inheritence is not possible in Structures in C#.NET?

-Structures are value types and derived from System.ValueType.
-Value types are always sealed so that inheritence not possible from value types

11) How to restrict the other classes to change the Title of the class in C#.NET?

Using private to set method.

public string Title {get; private set;}

12)Can we assign default value to properties in C#.NET?

Yes . You can assign.

public string StudentName {get;  set;} = string.Empty;

13)What is Tuples in C#.NET?

-Tuple is a light weight data structure in C#.NET, used to represent multiple output values from a method call.

public class Example 
{
public static void main()
{
var result = CountryData("India");

var country = result.Item1'
var population = result.Item2;
var states = result.Item3;

//body of the method
}

private static (string,int,double) CountryData(string cname)
{
if(cname == "India")
      return (cname,140000000,29);
if(cname == "UK")
       return (cname,6000000,20);
return ("",0,0);
}
}

you can retrieve the values in multiple ways.

(string country,int population,int noOfStates) =  CountryData("India");

(or)

var (country,population,noOfStates) =  CountryData("India");

(or)

string country;
int population;
int noOfStates;

(country,population,noOfStates) =  CountryData("India");

14)What is Discards in C#.NET?


-Discards added in C#7.0.
-Using disacrds to represent the unused return values.
-Some times we may not use all the return values from method call,to represent the this unused values using the discards


(_, _ ,noOfStates) =  CountryData("India");

Form the above methods call using only noOfStates values, not using other values so that represent the  with discards 

15)What is null-forgiving operator (!) in C#.NET?

-This feature added to the C#.NET8.0
-This operator also called null-suppression operator.
-Main purpose of this operator is to supress the warnings related to the null
-By using this operator informed to compiler that passing null is as expected so that dont show warning message

[Required]
public string StudentName {get;set;} = null!;

16)What is mutable , immutable data types in C#.NET?

- mutable data types can be modified after creation

-immutable data types cannot be modified after creation

17)What is Lazy<T> class in .NET?

Lazy<T> is used to support lazy initialization. Where T is the type of the object that is initialized lazily.
Lazy<Student> lazyStudentObject= new Lazy<Student>();

18) What is Static Imports in C#.NET? (or)  How to apply Static modifier to using directive?

using directives allows us to use namespace members without specifying its complete name.  

syntax:

using static <fully qualified type name>;

namespace System
{
 public static class Math
    {
public static double Sqrt(double d);
   }
}

using System;
using System.Reflection;
using static System.Math;

namespace ConsoleApp2
{
    class Program
    {
      static void Main(string[] args)
        {
            int x= 5;
            Console.WriteLine(Sqrt(5));
            Console.ReadKey();
        }
    }
}

0/p : 2.23606797749979
using static imports only accessible static members and nested types . Inherited members aren't imported.

19)What is when keyword in C#.NET? (or) How to filter exceptions in C#.NET?

Using when keyword , filter the exception message.
 class Program

    {
        static void Main(string[] args)
        {
            int num =0;
            int num1 = 5;
            int res;
            try
            {
                res = num1 / num;
                
            }
            catch (Exception ex) when (ex.Message.Equals("Attempted to divide by zero."))
            {
                res = 0;
            }
            Console.WriteLine("result values  " + res);
            Console.ReadKey();
        }
        }

20)What is Range operator in C#.NET?

.. is range operator 
x..y 
The left operand is an inclusive start of a range
The right-hand operand is an exclusive end of a range

 public static void Main(string[] args)
        { 
            char[] A = {'A','B','C','D','E','F','G'};
            Console.WriteLine(A[2..6]);
            Console.ReadLine();
        }

OUTPUT: CDEF


17) What is Init only setters in C#.NET?

  For Part1 clickhere

Thanks for visiting this blog. How is the content?. Your comment is great gift to my work. Cheers.







No comments:

Post a Comment