YouTube Icon

Interview Questions.

Top 50 C#. Net Interview Questions - Jul 25, 2022

fluid

Top 50 C#. Net Interview Questions

Q1. What's The Role Of The Datareader Class In Ado.Internet Connections?

It returns a examine-best dataset from the statistics source while the command is achieved.

Q2. When Do We Generally Use Destructors To Release Resources?

If the application uses unmanaged resources consisting of windows, files, and community connections, we use

destructors to launch resources.

Q3. How Do I Get Deterministic Finalization In C#?

In a garbage gathered environment, it's impossible to get true determinism. However, a design sample that we propose is imposing IDisposable on any class that contains a crucial aid. Whenever this class is ate up, it could be placed in a the use of declaration, as shown inside the following example:

the use of(FileStream myFile = File.Open(@"c:temptest.Txt", FileMode.Open))

int fileOffset = 0;

whilst(fileOffset < myFile.Length)

Console.Write((char)myFile.ReadByte());

fileOffset++;

 

When myFile leaves the lexical scope of the using, its dispose method may be known as.

Q4. How Do You Determine Whether A String Represents A Numeric Value?

To determine whether or not a String represents a numeric cost use TryParse approach as proven in the instance below. If the string carries nonnumeric characters or the numeric fee is simply too huge or too small for the particular type you've got exact, TryParse returns fake and sets the out parameter to zero. Otherwise, it returns authentic and sets the out parameter to the numeric value of the string.

String str = "One";

int i = zero;

if(int.TryParse(str,out i))

Console.WriteLine("Yes string incorporates Integer and it's far " + i);

else

Console.WriteLine("string does not include Integer");

 

Q5. A Class Inherits From 2 Interfaces And Both The Interfaces Have The Same Method Name As Shown Below. How Should The Class Implement The Drive Method For Both Car And Bus Interface?

Namespace Interfaces

interface Car

void Drive();

interface Bus

void Drive();

magnificence Demo : Car,Bus

//How to put in force the Drive() Method inherited from Bus and Car

To put into effect the Drive() method use the absolutely qualified call as proven in the example under. To call the respective interface power approach kind solid the demo object to the respective interface and then call the power method.

The usage of System;

namespace Interfaces

interface Car

void Drive();

interface Bus

void Drive();

elegance Demo : Car,Bus

void Car.Drive()

Console.WriteLine("Drive Car");

void Bus.Drive()

Console.WriteLine("Drive Bus");

static void Main()

Demo DemoObject = new Demo();

((Car)DemoObject).Drive();

((Bus)DemoObject).Drive();

 

Q6. What Are Constants In C#?

Constants in C# are immutable values which might be recognized at collect time and do now not exchange for the existence of this system. Constants are declared using the const key-word. Constants need to be initialized as they're declared. You cannot assign a price to a consistent after it isdeclared. An instance is shown underneath.

The use of System;

elegance Circle

public const double PI = three.14;

public Circle()

//Error : You can simplest assign a fee to a consistent area at the time of declaration

//PI = three.15;

 

magnificence MainClass

public static void Main()

Console.WriteLine(Circle.PI);

Q7. Will The Following Code Compile And Run?

String str = null;

Console.WriteLine(str.Length);

The above code will compile, however at runtime System.NullReferenceException will be thrown

Q8. Are C# References The Same As C++ References?

Not quite. The simple concept is the equal, but one significant difference is that C# references can be null . So you can not rely on a C# reference pointing to a valid object. In that admire a C# reference is extra like a C++ pointer than a C++ reference. If you try and use a null reference, a NullReferenceException is thrown.

For example, examine the following method:

void displayStringLength( string s )

Console.WriteLine( "String is period 0", s.Length );

The trouble with this technique is that it'll throw a NullReferenceException if called like this:

string s = null;

displayStringLength( s );

Of direction for some situations you could deem a NullReferenceException to be a superbly appropriate final results, but in this example it might be higher to re-write the method like this:

void displayStringLength( string s )

if( s == null )

Console.WriteLine( "String is null" );

else

Console.WriteLine( "String is duration zero", s.Length );

 

Q9. What Are Three Test Cases You Should Go Through In Unit Testing?

Positive check cases (correct information, accurate output), bad test cases (damaged or lacking records, right coping with), exception take a look at cases (exceptions are thrown and caught properly).

Q10. Can You Instantiate A Struct Without Using A New Operator In C#?

Yes, you could instantiate a struct without using a new operator.

Q11. Is It True That All C# Types Derive From A Common Base Class?

Yes and no. All kinds may be handled as though they derive from item (System.Object), but with a view to deal with an example of a fee kind (e.G. Int, go with the flow) as item-derived, the instance have to be transformed to a reference kind the usage of a system called 'boxing'. In concept a developer can forget about approximately this and let the run-time fear about when the conversion is important, however in fact this implicit conversion will have facet-results which could ride up the unwary.

Q12. What Do You Know About .Internet Assemblies?

Assemblies are the smallest devices of versioning and deployment inside the .NET software. Assemblies are also the building blocks for programs consisting of Web services, Windows offerings, serviced additives, and .NET remoting programs.

Q13. What Are Access Modifiers Used For?

Access Modifiers are used to control the accessibilty of types and members with inside the kinds.

Q14. What Is The Difference Between A Struct And A Class In C#?

From language spec:

The listing of similarities between classes and structs is as follows. Longstructs can put in force interfaces and can have the same varieties of individuals as instructions. Structs range from lessons in numerous crucial approaches; but, structs are fee sorts rather than reference sorts, and inheritance isn't supported for structs. Struct values are saved at the stack or in-line. Careful programmers can sometimes enhance overall performance thru judicious use of structs. For instance, using a struct as opposed to a category for a Point can make a big distinction within the quantity of reminiscence allocations carried out at runtime. The program below creates and initializes an array of 100 factors. With Point carried out as a category, one hundred and one separate items are instantiated-one for the array and one every for the 100 factors.

Q15. Is It Possible To Have Different Access Modifiers On The Get/set Methods Of A Property?

No. The get right of entry to modifier on a property applies to both its get and set accessors. What you need to do in case you need them to be special is make the assets study-handiest (via simplest imparting a get accessor) and create a non-public/inner set approach this is break free the assets.

Q16. If You Define A User Defined Data Type By Using The Struct Keyword, Is It A Value Type Or Reference Type?

Value Type.

Q17. What Is The Difference Between String Keyword And System.String Class?

String keyword is an alias for Syste.String elegance. Therefore, System.String and string keyword are the equal, and you may use whichever naming convention you prefer. The String elegance presents many strategies for safely growing, manipulating, and comparing strings.

Q18. Can Structs In C# Have Destructors?

No, structs may have constructors but no longer destructors, handiest lessons could have destructors.

Q19. If C# Destructors Are So Different To C++ Destructors, Why Did Ms Use The Same Syntax?

Presumably they desired C++ programmers to feel at home. I suppose they made a mistake.

Q20. Explain What Is An Interface In C#?

An Interface in C# is created the use of the interface key-word. An instance is shown under.

The use of System;

namespace Interfaces

interface IBankCustomer

void DepositMoney();

void WithdrawMoney();

public elegance Demo : IBankCustomer

public void DepositMoney()

Console.WriteLine("Deposit Money");

public void WithdrawMoney()

Console.WriteLine("Withdraw Money");

public static void Main()

Demo DemoObject = new Demo();

DemoObject.DepositMoney();

DemoObject.WithdrawMoney();

 

In our instance we created IBankCustomer interface. The interface pronounces 2 methods.

@void DepositMoney();

@void WithdrawMoney();

Notice that technique declarations does no longer have get admission to modifiers like public, private, etc. By default all interface contributors are public. It is a assemble time blunders to use access modifiers on interface member declarations. Also be aware that the interface techniques have best declarations and no longer implementation. It is a bring together time error to offer implementation for any interface member. In our example as the Demo elegance is inherited from the IBankCustomer interface, the Demo magnificence has to offer the implementation for both the strategies (WithdrawMoney() and DepositMoney()) this is inherited from the interface. If the elegance fails to offer implementation for any of the inherited interface member, a compile time error can be generated. Interfaces can include methods, houses, events, indexers, or any mixture of those 4 member types. When a class or a struct inherits an interface, the class or struct should provide implementation for all of the participants declared inside the interface. The interface itself offers no functionality that a category or struct can inherit in the manner that base elegance functionality may be inherited. However, if a base elegance implements an interface, the derived magnificence inherits that implementation.

Q21. Explain The Three Services Model Commonly Know As A Three-tier Application.

Presentation (UI), Business (common sense and underlying code) and Data (from storage or other resources).

Q22. Where Is The Output Of Textwritertracelistener Redirected?

To the Console or a textual content document depending on the parameter exceeded to the constructor.

Q23. What's The .Net Datatype That Allows The Retrieval Of Data By A Unique Key?

HashTable.

Q24. Difference Between A Sub And A Function.

A Sub does now not return something whereas a Function returns some thing.

-A Sub Procedure is a technique will now not go back a cost

-A sub manner will be described with a “Sub” key-word

Sub ShowName(ByVal myName As String)

Console.WriteLine(”My call is: ” & myName)

End Sub

-A function is a technique with the intention to return fee(s).

-A feature may be described with a “Function” keyword

Function FindSum(ByVal num1 As Integer, ByVal num2 As Integer) As Integer

Dim sum As Integer = num1 + num2

Return sum

End Function

Q25. Can You Declare An Override Method To Be Static If The Original Method Is Not Static?

No. The signature of the virtual technique need to remain the identical. (Note: Only the key-word virtual is changed to key-word override)

Q26. What Does The Keyword "virtual" Declare For A Method Or Property?

The technique or assets can be overridden.

Q27. Give An Example To Show For Hiding Base Class Methods?

Use the new keyword to hide a base magnificence technique within the derived class as shown in the instance beneath.

The usage of System;

public magnificence BaseClass

public virtual void Method()

Console.WriteLine("I am a base class technique.");

 

public magnificence DerivedClass : BaseClass

public new void Method()

Console.WriteLine("I am a infant magnificence method.");

public static void Main()

DerivedClass DC = new DerivedClass();

DC.Method();

Q28. Structs Are Not Reference Types. Can Structs Have Constructors?

Yes, even though Structs are not reference sorts, structs will have constructors.

Q29. Is There A Way Of Specifying Which Block Or Loop To Break Out Of When Working With Nested Loops?

The easiest manner is to use goto:

the use of System;

elegance BreakExample

public static void Main(String[] args)

for(int i=zero; i<3; i++)

Console.WriteLine("Pass 0: ", i);

for( int j=zero ; j<a hundred ; j++ )

if ( j == 10) goto finished;

Console.WriteLine("zero ", j);

Console.WriteLine("This will no longer print");

executed:

Console.WriteLine("Loops entire.");

Q30. If A Child Class Instance Is Created, Which Class Constructor Is Called First - Base Class Or Child Class?

When an example of a infant elegance is created, the base magnificence constructor is referred to as before the child magnificence constructor. An example is shown below.

The usage of System;

namespace TestConsole

elegance BaseClass

public BaseClass()

Console.WriteLine("I am a base elegance constructor");

 

class ChildClass : BaseClass

public ChildClass()

Console.WriteLine("I am a baby class constructor");

public static void Main()

ChildClass CC = new ChildClass();

 

Q31. How Do I Create A Delegate/multicastdelegate?

C# requires only a unmarried parameter for delegates: the method address. Unlike different languages, where the programmer have to specify an object reference and the method to invoke, C# can infer both pieces of records by just specifying the approach's call. For instance, allow's use System.Threading.ThreadStart: Foo MyFoo = new Foo(); ThreadStart del = new ThreadStart(MyFoo.Baz); This me that delegates can invoke static magnificence techniques and instance techniques with the precise equal syntax!

Q32. Does C# Support Multiple Inheritance?

No, use interfaces as a substitute.

Q33. Will The Finally Block Get Executed If An Exception Has Not Occurred?

Yes. Finally block constantly get accomplished.

Q34. What Are Access Modifiers In C#?

In C# there are five one-of-a-kind styles of Access Modifiers.

Public

The public type or member can be accessed via every other code within the identical meeting or another meeting that references it.

Private

The kind or member can best be accessed via code within the same elegance or struct.

Protected

The type or member can simplest be accessed via code within the same elegance or struct, or in a derived class.

Internal

The type or member can be accessed by any code in the identical assembly, however not from any other meeting.

Protected Internal

The kind or member can be accessed by any code within the same assembly, or by any derived magnificence in another assembly.

Q35. Difference Between Imperative And Interrogative Code.

There are imperative and interrogative capabilities. Imperative features are the only which return a fee at the same time as the interrogative features do not go back a price.

Q36. Is It Possible To Force Garbage Collector To Run?

Yes, it feasible to pressure garbage collector to run by way of calling the Collect() approach, however this is not taken into consideration an excellent practice due to the fact this could create a performance over head. Usually the programmer has no manage over whilst the garbage collector runs. The garbage collector assessments for items which are not being utilized by the application. If it considers an object eligible for destruction, it calls the destructor(if there may be one) and reclaims the memory used to save the object.

Q37. What Types Of Object Can I Throw As Exceptions?

Only instances of the System.Exception lessons, or instructions derived from System.Exception. This is in sharp evaluation with C++ where times of almost any kind can be thrown.

Q38. What Is A Partial Class. Give An Example?

A partial elegance is a category whose definition is present in 2 or more documents. Each source record carries a phase of the elegance, and all components are blended whilst the application is compiled. To split a class definition, use the partial key-word as proven in the instance below. Student magnificence is cut up into 2 parts. The first element defines the have a look at() method and the second part defines the Play() technique. When we bring together this application each the parts could be combined and compiled. Note that each the parts makes use of partial key-word and public get right of entry to modifier.

The use of System;

namespace PartialClass

public partial magnificence Student

public void Study()

Console.WriteLine("I am studying");

 

public partial class Student

public void Play()

Console.WriteLine("I am Playing");

 

public magnificence Demo

public static void Main()

Student StudentObject = new Student();

StudentObject.Study();

StudentObject.Play();
 

It is very essential to preserve the following factors in thoughts when developing partial training.

@All the elements ought to use the partial key-word.

@All the components should be to be had at bring together time to form the very last magnificence.

@All the components have to have the identical get admission to modifiers - public, personal, protected etc.

@Any class members declared in a partial definition are available to all of the different elements.

@The final magnificence is the mixture of all of the components at assemble time.

Q39. What Happens If A Static Constructor Throws An Exception?

If a static constructor throws an exception, the runtime will no longer invoke it a second time, and the type will continue to be uninitialized for the lifetime of the application area in which your program is strolling.

Q40. What Is The Wildcard Character In Sql?

Let’s say you need to question database with LIKE for all employees whose name starts with La. The wildcard person is %, the right query with LIKE would involve ‘La%’.

Q41. What Happens In Memory When You Box And Unbox A Value-type?

Boxing converts a fee-kind to a reference-kind, as a consequence storing the item at the heap. Unboxing converts a reference-kind to a fee-kind, thus storing the cost at the stack.

Q42. Describe The Accessibility Modifier Protected Internal?

It is available to derived classes and training in the identical Assembly (and clearly from the base magnificence it's far declared in).

Q43. Can You Declare A Field Readonly?

Yes, a subject may be declared readonly. A examine-handiest field can only be assigned a cost for the duration of initialization or in a constructor. An example is shown under.

The use of System;

magnificence Area

public readonly double PI = 3.14;

magnificence MainClass

public static void Main()

Area A = new Area();

Console.WriteLine(A.PI);

Q44. Who Is A Protected Class-degree Variable Available To?

It is to be had to any sub-class (a class inheriting this class).

Q45. Can You Mark Static Constructor With Access Modifiers?

No, we cannot use get admission to modifiers on static constructor.

Q46. Is The Following Code Legal?

The usage of System;

namespace Demo

elegance Program

public static void Main()

 

public void Sum(int FirstNumber, int SecondNumber)

int Result = FirstNumber + SecondNumber;

public int Sum(int FirstNumber, int SecondNumber)

int Result = FirstNumber + SecondNumber;

 

No, The above code does now not compile. You can not overload a technique based on the return kind. To overload a way in C# either the number or form of parameters should be exceptional. In widespread the go back type of a way isn't a part of the signature of the technique for the functions of method overloading. However, it is a part of the signature of the approach when determining the compatibility between a delegate and the technique that it factors to.

Q47. What's The C# Equivalent Of C++ Catch (...), Which Was A Catch-all Statement For Any Possible Exception?

A capture block that catches the exception of type System.Exception. You also can omit the parameter statistics type in this case and simply write capture .

Q48. What Is Wrong With The Sample Program Below?

The usage of System;

elegance Area

public const double PI = 3.14;

static Area()

Area.PI = 3.15;

 

class MainClass

public static void Main()

Console.WriteLine(Area.PI);

 

You cannot assign a value to the regular PI subject.

Q49. Where's Global Assembly Cache Located On The System?

Usually C:winntassembly or C:windowsassembly.

Q50. What Does Protected Internal Access Modifier Mean?

The protected internal get right of entry to me blanketed OR inner, no longer included AND internal. In easy phrases, a blanketed internal member is obtainable from any class inside the same meeting, together with derived lessons. To limit accessibility to most effective derived instructions inside the identical meeting, claim the magnificence itself inner, and claim its participants as protected.




CFG