YouTube Icon

Interview Questions.

Top 100+ C#. Net Interview Questions And Answers - May 28, 2020

fluid

Top 100+ C#. Net Interview Questions And Answers

Question 1. What's The Advantage Of Using System.Textual content.Stringbuilder Over System.String?

Answer : StringBuilder is extra green in the instances, where quite a few manipulation is performed to the textual content. Strings are im mutable, so on every occasion it’s being operated on, a new example is created.

Question 2. Can You Store Multiple Data Types In System.Array?

Answer : No.

C++ Interview Questions
Question 3. What's The Difference Between The System.Array.Copyto() And System.Array.Clone()?

Answer :

The first one plays a deep copy of the array, the second one is shallow.

Question four. How Can You Sort The Elements Of The Array In Descending Order?

Answer :

By calling Sort() after which Reverse() methods.

C++ Tutorial
Question five. What's The .Net Datatype That Allows The Retrieval Of Data By A Unique Key?

Answer :

HashTable.

VB.NET Interview Questions
Question 6. What's Class Sortedlist Underneath?

Answer :

A looked after HashTable.

Question 7. Will Finally Block Get Executed If The Exception Had Not Occurred?

Answer :

Yes.

VB.NET Tutorial C Interview Questions
Question 8. What's The C# Equivalent Of C++ Catch (....), Which Was A Catch-all Statement For Any Possible Exception?

Answer :

A trap block that catches the exception of type System.Exception. You also can pass over the parameter statistics kind in this situation and simply write capture .

Question nine. Can Multiple Catch Blocks Be Executed?

Answer :

No, once the right seize code fires off, the manipulate is transferred to the sooner or later block (if there are any), after which anything follows the in the end block.

ADO.Net Interview Questions
Question 10. Why Is It A Bad Idea To Throw Your Own Exceptions?

Answer :

Well, if at that point you know that an errors has happened, then why not write the right code to deal with that mistakes as opposed to passing a new Exception object to the catch block? Throwing your own exceptions signifies a few layout flaws within the task.

C#. NET Tutorial
Question 11. What's A Delegate?

Answer :

A delegate item encapsulates a connection with a method. In C++ they have been called function tips.

MVC Framework Interview Questions
Question 12. What's A Multicast Delegate?

Answer :

It’s a delegate that factors to and ultimately fires off several methods.

C++ Interview Questions
Question thirteen. How's The Dll Hell Problem Solved In .Internet?

Answer :

Assembly versioning lets in the software to specify no longer most effective the library it wishes to run (which turned into to be had beneath Win32), but additionally the model of the meeting.

C Tutorial
Question 14. What Are The Ways To Deploy An Assembly?

Answer :

An MSI installer, a CAB archive, and XCOPY command.

Question 15. What's A Satellite Assembly?

Answer :

When you write a multilingual or multi-cultural application in .NET, and need to distribute the middle software one at a time from the localized modules, the localized assemblies that modify the middle utility are referred to as satellite tv for pc assemblies.

LINQ Interview Questions
Question sixteen. What Namespaces Are Necessary To Create A Localized Application?

Answer :

System.Globalization, System.Resources.

MVC Framework Tutorial
Question 17. What's The Difference Between // Comments, /* */ Comments And /// Comments?

Answer :

Single-line, multi-line and XML documentation feedback.

Windows Presentation Foundation(WPF) Interview Questions
Question 18. How Do You Generate Documentation From The C# File Commented Properly With A Command-line Compiler?

Answer :

Compile it with a /doc switch.

VB.NET Interview Questions
Question 19. What's The Difference Between <c> And <code> Xml Documentation Tag?

Answer :

Single line code instance and multiple-line code example.

LINQ Tutorial
Question 20. Is Xml Case-sensitive?

Answer :

Yes, so <Student> and <student> are unique factors.

Windows Communication Foundation (WCF) Interview Questions
Question 21. What Debugging Tools Come With The .Net Sdk?

Answer :

CorDBG – command-line debugger, and DbgCLR – photograph debugger. Visual Studio .NET uses the DbgCLR. To use CorDbg, you ought to compile the authentic C# record the usage of the /debug switch.

Question 22. What Does The This Window Show In The Debugger?

Answer :

It points to the item that’s pointed to by way of this reference. Object’s instance information is proven.

Windows Presentation Foundation(WPF) Tutorial
Question 23. What Does Assert() Do?

Answer :

In debug compilation, assert takes in a Boolean situation as a parameter, and indicates the mistake dialog if the circumstance is false. The software proceeds with none interruption if the situation is actual.

Advanced C# Interview Questions
Question 24. What's The Difference Between The Debug Class And Trace Class? Documentation Looks The Same.

Answer :

Use Debug magnificence for debug builds, use Trace elegance for both debug and release builds.

C Interview Questions
Question 25. Why Are There Five Tracing Levels In System.Diagnostics.Traceswitcher?

Answer :

The tracing dumps can be pretty verbose and for some programs which can be continuously jogging you run the risk of overloading the device and the difficult drive there. Five levels variety from None to Verbose, permitting to nice-track the tracing activities.

Windows Communication Foundation (WCF) Tutorial
Question 26. Where Is The Output Of Textwritertracelistener Redirected?

Answer :

To the Console or a text record depending at the parameter exceeded to the constructor.

C# Developer Multi Threading Interview Questions
Question 27. How Do You Debug An Asp.Internet Web Application?

Answer :

Attach the aspnet_wp.Exe system to the DbgClr debugger.

ADO.Net Interview Questions
Question 28. What Are Three Test Cases You Should Go Through In Unit Testing?

Answer :

Positive test cases (accurate information, correct output), poor take a look at cases (broken or lacking facts, proper managing), exception check cases (exceptions are thrown and stuck nicely).

Question 29. Can You Change The Value Of A Variable While Debugging A C# Application?

Answer :

Yes, in case you are debugging thru Visual Studio.NET, just go to Immediate window.

Asp Dot Net Mvc 4 Interview Questions
Question 30. Explain The Three Services Model (3-tier Application).

Answer :

Presentation (UI), enterprise (common sense and underlying code) and information (from garage or other sources).

Question 31. What Are Advantages And Disadvantages Of Microsoft-provided Data Provider Classes In Ado.Net?

Answer :

SQLServer.NET statistics company is high-velocity and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is established for having access to other assets, like Oracle, DB2, Microsoft Access and Informix, but it’s a .NET layer on top of OLE layer, so no longer the fastest aspect within the world. ODBC.NET is a deprecated layer supplied for backward compatibility to ODBC engines.

Question 32. What's The Role Of The Datareader Class In Ado.Net Connections?

Answer :

It returns a study-handiest dataset from the statistics source while the command is carried out.

Asp Dot Net Mvc Interview Questions
Question 33. What Is The Wildcard Character In Sql? Let's Say You Want To Query Database With Like For All Employees Whose Name Starts With La.

Answer :

The wildcard character is %, the proper query with LIKE might contain ‘La%’.

MVC Framework Interview Questions
Question 34. Explain Acid Rule Of Thumb For Transactions.

Answer :

Transaction must be Atomic (it is one unit of work and does now not depending on preceding and following transactions), Consistent (information is either dedicated or roll back, no “in-between” case in which some thing has been updated and something hasn’t), Isolated (no transaction sees the intermediate consequences of the cutting-edge transaction), Durable (the values persist if the facts were dedicated even though the device crashes proper after).

Question 35. What Connections Does Microsoft Sql Server Support?

Answer :

Windows Authentication (through Active Directory) and SQL Server authentication (through Microsoft SQL Server consumer call and passwords).

Question 36. Which One Is Trusted And Which One Is Untrusted?

Answer :

Windows Authentication is trusted because the username and password are checked with the Active Directory, the SQL Server authentication is untrusted, because SQL Server is the most effective verifier taking part within the transaction.

LINQ Interview Questions
Question 37. Why Would You Use Untrusted Verificaion?

Answer :

Web Services might use it, in addition to non-Windows programs.

Question 38. What Does The Parameter Initial Catalog Define Inside Connection String?

Answer :

The database name to connect to.

Question 39. What's The Data Provider Name To Connect To Access Database?

Answer :

Microsoft.Access.

Question forty. What Does Dispose Method Do With The Connection Object?

Answer :

Deletes it from the reminiscence.

Windows Presentation Foundation(WPF) Interview Questions
Question 41. What Is A Pre-considered necessary For Connection Pooling?

Answer :

Multiple methods ought to agree that they will proportion the equal connection, where each parameter is the same, along with the safety settings.

Question 42. What Is C#?

Answer :

C# is a programming language designed by Microsoft. It is loosely based on C/C++, and bears a striking similarity to Java. Microsoft describe C# as follows:

"C# is a simple, modern, item orientated, and kind-secure programming language derived from C and C++. C# (reported 'C sharp') is firmly planted in the C and C++ circle of relatives tree of languages, and could immediately be familiar to C and C++ programmers. C# targets to combine the excessive productiveness of Visual Basic and the uncooked strength of C++."

Windows Communication Foundation (WCF) Interview Questions
Question forty three. How Do I Develop C# Apps?

Answer :

The (unfastened) .NET SDK carries the C# command-line compiler (csc.Exe). Visual Studio has completely included aid for C# improvement. On Linux you can use Mono.

Question 44. Does C# Replace C++?

Answer :

There are 3 alternatives open to the Windows developer from a C++ historical past:

•Stick with fashionable C++. Don't use .NET in any respect.
•Use C++ with .NET. Microsoft deliver a .NET C++ compiler that produces IL in place of gadget code. However to make complete use of the .NET environment (e.G. Rubbish collection), a fixed of extensions are required to standard C++. In .NET 1.X this prolonged language is referred to as Managed Extensions for C++. In .NET 2.0 ME C++ has been completely redesigned under the stewardship of Stan Lippman, and renamed C++/CLI.
•Forget C++ and use C#.

Each of these options has deserves, depending on the developer and the software. For my personal component, I intend to apply C# wherein possible, falling lower back to C++ simplest where necessary. ME C++ (soon to be C++/CLI) could be very useful for interop among new .NET code and vintage C++ code - in reality write a managed wrapper elegance the usage of ME C++, then use the controlled elegance from C#. From enjoy, this works nicely.

Question forty five. Does C# Have Its Own Class Library?

Answer :

Not exactly. The .NET Framework has a complete class library, which C# can make use of. C# does now not have its own class library.

Question forty six. What Standard Types Does C# Use?

Answer :

C# supports a very comparable range of basic kinds to C++, consisting of int, lengthy, go with the flow, double, char, string, arrays, structs and classes. However, do not count on too much. The names may be familiar, however many of the info are specific. For example, an extended is 64 bits in C#, whereas in C++ the scale of a protracted relies upon at the platform (usually 32 bits on a 32-bit platform, sixty four bits on a 64-bit platform). Also instructions and structs are almost the equal in C++ - this isn't always true for C#. Finally, chars and strings in .NET are sixteen-bit (Unicode/UTF-16), not 8-bit like C++.

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

Answer :

Yes and no. All sorts may be treated as though they derive from item (System.Object), however that allows you to treat an instance of a fee kind (e.G. Int, drift) as item-derived, the example need to be transformed to a reference kind using a process referred to as 'boxing'. In concept a developer can forget approximately this and let the run-time fear approximately while the conversion is necessary, however in fact this implicit conversion could have side-effects that can trip up the unwary.

Question 48. What Are The Fundamental Differences Between Value Types And Reference Types?

Answer :

C# divides types into  categories - cost types and reference types. Most of the intrinsic kinds (e.G. Int, char) are cost kinds. Structs also are value sorts. Reference sorts include training, arrays and strings. The simple concept is easy - an example of a cost kind represents the real facts, whereas an instance of a reference kind represents a pointer or reference to the facts.

The most difficult component of this for C++ developers is that C# has predetermined which types are represented as values, and which are represented as references. A C++ developer expects to take responsibility for this choice.

For example, in C++ we can try this:
int x1 = 3; // x1 is a cost at the stack
int *x2 = new int(three) // x2 is a pointer to a price at the heap
but in C# there's no manage:
int x1 = 3; // x1 is a price on the stack
int x2 = new int();
x2 = 3; // x2 is also a value at the stack!

Question 49. Okay, So An Int Is A Value Type, And A Class Is A Reference Type. How Can Int Be Derived From Object?

Answer :

It is not, actually. When an int is getting used as an int, it is a cost. However, while it's far being used as an object, it's miles a connection with an integer fee (at the managed heap). In different phrases, when you deal with an int as an object, the runtime robotically converts the int fee to an object reference. This method is known as boxing. The conversion involves copying the int to the heap, and developing an object example which refers to it. Unboxing is the opposite procedure - the object is transformed back to a value.

Int x = three; // new int price three at the stack
object objx = x; // new int on heap, set to price 3 - still have x=3 on stack
int y = (int)objx; // new fee 3 on stack, still got x=three on stack and objx=three on heap

Question 50. Are C# References The Same As C++ References?

Answer :

Not quite. The simple idea is the equal, but one massive difference is that C# references may be null . So you cannot depend on a C# reference pointing to a valid object. In that recognize a C# reference is greater like a C++ pointer than a C++ reference. If you try to use a null reference, a NullReferenceException is thrown.

For example, look at the subsequent method:
void displayStringLength( string s )

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

The trouble with this approach is that it'll throw a NullReferenceException if called like this:
string s = null;
displayStringLength( s );

Of path for some conditions you could deem a NullReferenceException to be a superbly suited outcome, however in this example it is probably 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 0", s.Length );


Question fifty one. Structs Are Largely Redundant In C++. Why Does C# Have Them?

Answer :

In C++, a struct and a category are pretty a good deal the identical factor. The best difference is the default visibility stage (public for structs, private for instructions). However, in C# structs and instructions are very one-of-a-kind. In C#, structs are fee kinds (times stored without delay on the stack, or inline inside heap-primarily based objects), while training are reference types (instances stored on the heap, accessed in a roundabout way thru a reference). Also structs can't inherit from structs or instructions, although they can enforce interfaces. Structs can't have destructors. A C# struct is tons extra like a C struct than a C++ struct.

Question 52. Does C# Support Multiple Inheritance (mi)?

Answer :

No, though it does assist implementation of more than one interfaces on a single class or struct.

Question fifty three. Is A C# Interface The Same As A C++ Abstract Class?

Answer :

No, not pretty. An summary class in C++ can not be instantiated, however it may (and frequently does) comprise
implementation code and/or information members. A C# interface cannot incorporate any implementation code or records individuals - it is really a group of approach names & signatures. A C# interface is greater like a COM interface than a C++ abstract magnificence.

Question 54. Are C# Constructors The Same As C++ Constructors?

Answer :

Very similar, however there are some sizable differences. First, C# supports constructor chaining. This method one constructor can name any other:
class Person

public Person( string call, int age )  ... 
Public Person( string call ) : this( call, zero ) 
public Person() : this( "", 0 ) 


Another distinction is that virtual method calls within a constructor are routed to the maximum derived implementation - see Can I Call a digital technique from a constructor.

Error handling is likewise really extraordinary. If an exception takes place for the duration of construction of a C# item, the destuctor (finalizer) will nevertheless be referred to as. This is not like C++ where the destructor isn't known as if construction isn't finished. (Thanks to Jon Jagger for pointing this out.)

Finally, C# has static constructors. The static constructor for a category runs earlier than the first example of the class is created.

Also word that (like C++) a few C# builders prefer the factory method pattern over constructors. See Brad Wilson's article.

Question fifty five. Are C# Destructors The Same As C++ Destructors?

Answer :

No. They look the identical however they are very exceptional. The C# destructor syntax (with the familiar ~ character) is just syntactic sugar for an override of the System.Object Finalize approach. This Finalize technique is known as by using the garbage collector when it determines that an object is now not referenced, earlier than it frees the reminiscence related to the object. So a ways this appears like a C++ destructor. The distinction is that the rubbish collector makes no guarantees about while this process happens. Indeed, the set of rules employed by using the CLR garbage collector means that it could be a long term after the software has completed with the item. This lack of reality is frequently termed 'non-deterministic finalization', and it approach that C# destructors aren't appropriate for liberating scarce assets which includes database connections, document handles etc.

To achieve deterministic destruction, a class have to provide a technique for use for the cause. The popular method is for the elegance to put in force the IDisposable interface. The user of the item have to name the Dispose() method whilst it has completed with the object. C# gives the 'the use of' construct to make this simpler.

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

Answer :

Presumably they desired C++ programmers to experience at domestic. I assume they made a mistake.

Question fifty seven. Are All Methods Virtual In C#?

Answer :

No. Like C++, methods are non-digital by default, however can be marked as digital.

Question 58. How Do I Declare A Pure Virtual Function In C#?

Answer :

Use the abstract modifier on the method. The class have to additionally be marked as abstract (obviously). Note that abstract strategies cannot have an implementation (in contrast to pure digital C++ strategies).

Question 59. Can I Call A Virtual Method From A Constructor/destructor?

Answer :

Yes, but it is usually now not a very good concept. The mechanics of object creation in .NET are pretty exceptional from C++, and this impacts digital approach calls in constructors.

C++ constructs gadgets from base to derived, so while the bottom constructor is executing the object is efficaciously a base item, and virtual technique calls are routed to the bottom elegance implementation. By comparison, in .NET the derived constructor is carried out first, which means that the object is continually a derived object and digital method calls are constantly routed to the derived implementation. (Note that the C# compiler inserts a call to the base class constructor at the begin of the derived constructor, accordingly keeping preferred OO semantics by creating the illusion that the bottom constructor is finished first.)

The equal problem arises while calling digital methods from C# destructors. A virtual method name in a base destructor could be routed to the derived implementation.

Question 60. Should I Make My Destructor Virtual?

Answer :

A C# destructor is really simply an override of the System.Object Finalize method, and so is virtual via definition.

Question sixty one. Can I Use Exceptions In C#?

Answer :

Yes, in fact exceptions are the recommended error-handling mechanism in C# (and in .NET in fashionable). Most of the .NET framework instructions use exceptions to signal errors.

Question 62. What Types Of Object Can I Throw As Exceptions?

Answer :

Only instances of the System.Exception lessons, or classes derived from System.Exception. This is in sharp comparison with C++ in which instances of just about any type can be thrown.

Question 63. Can I Define My Own Exceptions?

Answer :

Yes, just derive your exception class from System.Exception.

Question sixty four. Does The System.Exception Class Have Any Cool Features?

Answer :

Yes - the characteristic which stands out is the StackTrace assets. This provides a call stack which facts wherein the exception turned into thrown from. For example, the following code:
using System;
magnificence CApp

public static void Main()

strive

f();

catch( Exception e )

Console.WriteLine( "System.Exception stack trace = n0", e.StackTrace );


static void f()

throw new Exception( "f went pear-shaped" );


produces this output:
System.Exception stack hint =
at CApp.F()
at CApp.Main()

Note, however, that this stack trace became created from a debug build. A release construct may additionally optimise away a number of the approach calls that may mean that the decision stack isn't always pretty what you assume.

Question 65. When Should I Throw An Exception?

Answer :

This is the challenge of a few debate, and is in part a matter of flavor. However, it's far normal by using many that exceptions have to be thrown only when an 'surprising' error takes place. How do you decide if an error is expected or sudden? This is a judgement name, however a honest instance of an expected errors is failing to read from a report because the searching for pointer is at the end of the record, whereas an instance of an unexpected errors is failing to allocate reminiscence from the heap.

Question 66. Does C# Have A 'throws' Clause?

Answer :

No, not like Java, C# does not require (or maybe permit) the developer to specify the exceptions that a technique can throw.

Question sixty seven. How Can I Check The Type Of An Object At Runtime?

Answer :

You can use the is key-word. For example:
the use of System;
elegance CApp

public static void Main()

string s = "fred";
lengthy i = 10;
Console.WriteLine( "zero is 1an integer", s, (IsInteger(s) ? "" : "now not ") );
Console.WriteLine( "zero is 1an integer", i, (IsInteger(i) ? "" : "not ") );

static bool IsInteger( item obj )
long )
go back actual;
else
return fake;


produces the output:
fred isn't always an integer
10 is an integer

Question 68. Can I Get The Name Of A Type At Runtime?

Answer :

Yes, use the GetType technique of the item magnificence (which all types inherit from). For example:
the use of System;
class CTest

magnificence CApp

public static void Main()

long i = 10;
CTest ctest = new CTest();
DisplayTypeInfo( ctest );
DisplayTypeInfo( i );

static void DisplayTypeInfo( item obj )

Console.WriteLine( "Type call = 0, complete type call = 1", obj.GetType(), obj.GetType().FullName );

produces the subsequent output:
Type call = CTest, complete type call = CTest
Type call = Int64, complete type call = System.Int64

Question sixty nine. How Do I Do A Case-insensitive String Comparison?

Answer :

Use the String.Compare characteristic. Its 0.33 parameter is a boolean which specifies whether or not case need to be overlooked or no longer.

"fred" == "Fred" // fake
System.String.Compare( "fred", "Fred", true ) // true

Question 70. Does C# Support A Variable Number Of Arguments?

Answer :

Yes, using the params keyword. The arguments are specified as a list of arguments of a selected type, e.G. Int. For remaining flexibility, the sort may be item. The preferred example of a way which uses this approach is System.Console.WriteLine().

Question 71. How Can I Process Command-line Arguments?

Answer :

Like this:
the usage of System;
elegance CApp

public static void Main( string[] args )

Console.WriteLine( "You exceeded the following arguments:" );
foreach( string arg in args )
Console.WriteLine( arg );

Question 72. Does C# Do Array Bounds Checking?

Answer :

Yes. An IndexOutOfRange exception is used to sign an blunders.

Question 73. How Can I Make Sure My C# Classes Will Interoperate With Other .Internet Languages?

Answer :

Make certain your C# code conforms to the Common Language Subset (CLS). To help with this, upload the [assembly:CLSCompliant(true)] international attribute for your C# supply files. The compiler will emit an blunders if you use a C# feature which isn't always CLS-compliant.

Question seventy four. How Do I Use The 'using' Keyword With Multiple Objects?

Answer :

You can nest the use of statements, like this:
the usage of( obj1 )

using( obj2 )

...

However bear in mind the usage of this greater aesthetically beautiful (but functionally same) formatting:
the use of( obj1 )
the usage of( obj2 )

...


Question seventy five. What Is The Difference Between == And Object.Equals?

Answer :

For cost kinds, == and Equals() generally evaluate  gadgets with the aid of cost. For instance:
int x = 10;
int y = 10;
Console.WriteLine( x == y );
Console.WriteLine( x.Equals(y) );
will show:
True
True

However matters are more complex for reference types. Generally speaking, for reference types == is anticipated to carry out an identity comparison, i.E. It will most effective go back genuine if both references factor to the identical item. By contrast, Equals() is anticipated to perform a cost comparison, i.E. It'll return authentic if the references factor to gadgets which might be equivalent. For example:
StringBuilder s1 = new StringBuilder("fred");
StringBuilder s2 = new StringBuilder("fred");
Console.WriteLine( s1 == s2 );
Console.WriteLine( s1.Equals(s2) );
will display:
False
True

s1 and s2 are different items (hence == returns false), however they are equivalent (subsequently Equals() returns genuine).

Unfortunately there are exceptions to these guidelines. The implementation of Equals() in System.Object (the only you'll inherit with the aid of default if you write a class) compares identification, i.E. It is similar to operator==. So Equals() most effective tests for equivalence if the elegance writer overrides the method (and implements it correctly). Another exception is the string class - its operator== compares price in preference to identification.

Bottom line: If you want to carry out an identification comparison use the ReferenceEquals() technique. If you need to carry out a price assessment, use Equals() but be conscious that it will handiest work if the sort has overridden the default implementation. Avoid operator== in regards types (except possibly strings), as it's simply too ambiguous.

Question seventy six. How Do I Enforce Const Correctness In C#?

Answer :

You can not - at least now not inside the identical manner you do in C++. C# (actually, the CLI) has no actual idea of const correctness, For instance, there's no manner to specify that a way should no longer modify a controversy handed in to it. And there may be no manner to specify that a way does now not adjust the item on which it's miles performing.

To get a sense for the angst this causes among a few C++ programmers, examine the feedback on this post from Raymond Chen.

There are of direction approaches of addressing this trouble. For instance, see Brad Abram's put up (and related comments) for some ideas on adding optionally available examine-best behaviour to collection classes.

Question 77. What Are The New Features In C# 2.Zero?

Answer :

Support for all of the new framework features such as generics, nameless methods, partial instructions, iterators and static training.

Delegate inference is a new characteristic of the C# compiler which makes delegate utilization a little simpler. It permits you to write this:
Thread t = new Thread(ThreadFunc);
in place of this:
Thread t = new Thread( new ThreadStart(ThreadFunc) );

Another minor however great addition is the express international namespace, which fixes a hollow in namespace usage in C# 1.X. You can prefix a type name with worldwide:: to suggest that the type belongs to the worldwide namespace, as a consequence keeping off problems where the compiler infers the namespace and gets it incorrect.

Finally C# 2.Zero includes a few syntactic sugar for the brand new System.Nullable type. You can use T? As a synonym for System.Nullable<T>, wherein T is a fee kind. As counseled by the name, this permits values of the sort to be 'null', or 'undefined'.

Question seventy eight. Are C# Generics The Same As C++ Templates?

Answer :

No, no longer without a doubt. There are some similarities, but there are also fundamental differences.

Question seventy nine. Explain What Is An Interface In C#?

Answer :

An Interface in C# is created using the interface keyword. An example is proven underneath.

The use of System;
namespace Interfaces

interface IBankCustomer

void DepositMoney();
void WithdrawMoney();

public class 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 example we created IBankCustomer interface. The interface declares 2 methods.
1. Void DepositMoney();
2. Void WithdrawMoney();

Notice that approach declarations does no longer have access modifiers like public, non-public, etc. By default all interface contributors are public. It is a assemble time blunders to use get entry to modifiers on interface member declarations. Also observe that the interface techniques have simplest declarations and now not implementation. It is a collect time mistakes to provide implementation for any interface member. In our instance because the Demo elegance is inherited from the IBankCustomer interface, the Demo elegance has to provide the implementation for each the strategies (WithdrawMoney() and DepositMoney()) this is inherited from the interface. If the class fails to offer implementation for any of the inherited interface member, a compile time mistakes could be generated. Interfaces can consist of techniques, properties, occasions, indexers, or any combination of these 4 member kinds. When a class or a struct inherits an interface, the magnificence or struct ought to provide implementation for all of the contributors declared within the interface. The interface itself provides no functionality that a class or struct can inherit within the way that base elegance capability can be inherited. However, if a base magnificence implements an interface, the derived magnificence inherits that implementation.

Question 80. Can An Interface Contain Fields?

Answer :

No, an Interface can not comprise fields.

Question 81. What Is The Difference Between Class Inheritance And Interface Inheritance?

Answer :

Classes and structs can inherit from interfaces much like how instructions can inherit a base elegance or struct. However there are 2 variations.
1. A magnificence or a struct can inherit from multiple interface on the equal time wherein as A elegance or a struct can not inherit from more than one class at the identical time. An instance depicting the identical is shown under.

Using System;
namespace Interfaces

interface Interface1

void Interface1Method();

interface Interface2

void Interface2Method();

elegance BaseClass1

public void BaseClass1Method()

Console.WriteLine("BaseClass1 Method");


magnificence BaseClass2

public void BaseClass2Method()

Console.WriteLine("BaseClass2 Method");


//Error : A elegance can't inherit from multiple magnificence at the same time
//class DerivedClass : BaseClass1, BaseClass2
//
//
//A elegance can inherit from more than one interface on the same time
public elegance Demo : Interface1, Interface2

public void Interface1Method()

Console.WriteLine("Interface1 Method");

public void Interface2Method()

Console.WriteLine("Interface2 Method");

public static void Main()

Demo DemoObject = new Demo();
DemoObject.Interface1Method();
DemoObject.Interface2Method();


2. When a class or struct inherits an interface, it inherits most effective the technique names and signatures, because the interface itself contains no implementations.

Question 82. Can An Interface Inherit From Another Interface?

Answer :

Yes, an interface can inherit from any other interface. It is feasible for a category to inherit an interface more than one instances, via base lessons or interfaces it inherits. In this case, the magnificence can simplest enforce the interface one time, if it's far declared as a part of the brand new class. If the inherited interface isn't declared as part of the brand new magnificence, its implementation is provided by the base class that declared it. It is feasible for a base magnificence to enforce interface individuals the usage of digital participants; in that case, the class inheriting the interface can change the interface conduct through overriding the virtual individuals.

Question 83. Can You Create An Instance Of An Interface?

Answer :

No, you cannot create an instance of an interface.

Question eighty four. If A Class Inherits An Interface, What Are The 2 Options Available For That Class?

Answer :

Option 1: Provide Implementation for all the individuals inheirted from the interface.

Namespace Interfaces

interface Interface1

void Interface1Method();

magnificence BaseClass1 : Interface1

public void Interface1Method()

Console.WriteLine("Interface1 Method");

public void BaseClass1Method()

Console.WriteLine("BaseClass1 Method");


Option 2: If the elegance does no longer want to provide Implementation for all the individuals inheirted from the interface, then the magnificence has to be marked as abstract.

Namespace Interfaces

interface Interface1

void Interface1Method();

summary magnificence BaseClass1 : Interface1

summary public void Interface1Method();
public void BaseClass1Method()

Console.WriteLine("BaseClass1 Method");


Question eighty five. 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?

Answer :

namespace Interfaces

interface Car

void Drive();

interface Bus

void Drive();

elegance Demo : Car,Bus

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

To put into effect the Drive() technique use the fully certified call as proven in the example below. To name the respective interface force technique kind solid the demo item to the respective interface after which call the drive method.

The usage of System;
namespace Interfaces

interface Car

void Drive();

interface Bus

void Drive();

magnificence 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();


Question 86. What Do You Mean By "explicitly Implemeting An Interface". Give An Example?

Answer :

If a class is imposing the inherited interface member by way of prefixing the call of the interface, then the elegance is "Explicitly Implemeting an Interface member". The disadvantage of Explicitly Implemeting an Interface member is that, the magnificence item has to be type casted to the interface type to invoke the interface member. An instance is shown below.

The usage of System;
namespace Interfaces

interface Car

void Drive();

magnificence Demo : Car

// Explicit implementation of an interface member
void Car.Drive()

Console.WriteLine("Drive Car");

static void Main()

Demo DemoObject = new Demo();
//DemoObject.Drive();
// Error: Cannot name explicitly implemented interface approach
// using the magnificence item.
// Type forged the demo object to interface kind Car
((Car)DemoObject).Drive();


Question 87. What Is A Partial Class. Give An Example?

Answer :

A partial magnificence is a class whose definition is present in 2 or more files. Each source record incorporates a segment of the class, and all components are mixed while the application is compiled. To break up a category definition, use the partial keyword as proven in the instance under. Student elegance is split into 2 elements. The first element defines the have a look at() approach and the second element defines the Play() technique. When we bring together this program each the components might be combined and compiled. Note that both the parts makes use of partial keyword and public get entry to modifier.

Using System;
namespace PartialClass

public partial magnificence Student

public void Study()

Console.WriteLine("I am analyzing");


public partial magnificence Student

public void Play()

Console.WriteLine("I am Playing");


public class Demo

public static void Main()

Student StudentObject = new Student();
StudentObject.Study();
StudentObject.Play();
 

It is very essential to keep the following points in thoughts when growing partial training.
1. All the components should use the partial key-word.
2. All the parts ought to be available at bring together time to shape the final class.
3. All the parts have to have the identical get admission to modifiers - public, personal, included etc.
4. Any magnificence members declared in a partial definition are to be had to all of the other parts.
Five. The very last magnificence is the combination of all the elements at collect time.

Question 88. What Are The Advantages Of Using Partial Classes?

Answer :

1. When running on large tasks, spreading a class over separate documents permits more than one programmers to paintings on it at the equal time.

2. When operating with automatically generated source, code may be delivered to the magnificence without having to recreate the source document. Visual Studio makes use of this method whilst it creates Windows Forms, Web service wrapper code, and so forth. You can create code that makes use of those training while not having to modify the record created through Visual Studio.

Question 89. Is It Possible To Create Partial Structs, Interfaces And Methods?

Answer :

Yes, it's far possible to create partial structs, interfaces and methods. We can create partial structs, interfaces and methods the same manner as we create partial lessons.

Question ninety. Will The Following Code Compile?

Answer :

using System;
namespace PartialClass

public partial magnificence Student

public void Study()

Console.WriteLine("I am analyzing");


public abstract partial magnificence Student

public void Play()

Console.WriteLine("I am Playing");


public magnificence Demo

public static void Main()

Student StudentObject = new Student();
 

No, a compile time blunders may be generated pointing out "Cannot create an example of the abstract class or interface "PartialClass.Student". This is due to the fact, if any component is asserted summary, then the entire class turns into summary. Similarly if any part is said sealed, then the entire class will become sealed and if any element declares a base elegance, then the whole class inherits that base elegance.

Question ninety one. Can You Create Partial Delegates And Enumerations?

Answer :

No, you cannot create partial delegates and enumerations.

Question 92. Can Different Parts Of A Partial Class Inherit From Different Interfaces?

Answer :

Yes, distinctive elements of a partial magnificence can inherit from unique interfaces.

Question ninety three. Can You Specify Nested Classes As Partial Classes?

Answer :

Yes, nested instructions can be distinctive as partial training even if the containing elegance is not partial. An instance is proven underneath.

Class ContainerClass

public partial class Nested

void Test1()  

public partial magnificence Nested

void Test2()  

Question ninety four. How Do You Create Partial Methods?

Answer :

To create a partial method we create the assertion of the method in a single part of the partial elegance and implementation in the other part of the partial magnificence. The implementation is non-obligatory. If the implementation isn't always supplied, then the method and all the calls to the approach are removed at compile time. Therefore, any code within the partial class can freely use a partial method, even if the implementation isn't provided. No compile-time or run-time errors will result if the method is called however not implemented. In summary a partial technique assertion includes  elements. The definition, and the implementation. These can be in separate elements of a partial class, or in the identical part. If there is no implementation assertion, then the compiler optimizes away each the defining assertion and all calls to the method.

The following are the factors to preserve in thoughts while growing partial techniques.
1. Partial approach declarations need to start partial keyword.
2. The return kind of a partial technique ought to be void.
Three. Partial strategies could have ref but now not out parameters.
4. Partial techniques are implicitly personal, and consequently they cannot be virtual.
Five. Partial techniques can not be extern, because the presence of the frame determines whether or not they're defining or imposing.

Question 95. What Is The Use Of Partial Methods?

Answer :

Partial methods may be used to customise generated code. They allow for a technique call and signature to be reserved, in order that generated code can name the approach but the developer can determine whether to put into effect the technique. Much like partial classes, partial strategies allow code created by using a code generator and code created with the aid of a human developer to paintings together without run-time charges.

Question 96. What Is A Nested Type. Give An Example?

Answer :

A kind(class or a struct) defined inside another class or struct is referred to as a nested kind. An instance is shown under. InnerClass is inner ContainerClass, Hence InnerClass is referred to as as nested magnificence.

The usage of System;
namespace Nested

magnificence ContainerClass

magnificence InnerClass

public string str = "A string variable in nested elegance";

public static void Main()

InnerClass nestedClassObj = new InnerClass();
Console.WriteLine(nestedClassObj.Str);


Question 97. Can The Nested Class Access, The Containing Class. Give An Example?

Answer :

Yes, the nested class, or inner magnificence can access the containing or outer magnificence as proven in the instance below. Nested kinds can get right of entry to personal and guarded individuals of the containing type, consisting of any inherited personal or covered contributors.

The use of System;
namespace Nested

elegance ContainerClass

string OuterClassVariable = "I am an outer class variable";
public class InnerClass

ContainerClass ContainerClassObject = new ContainerClass();
string InnerClassVariable = "I am an Inner elegance variable";
public InnerClass()

Console.WriteLine(ContainerClassObject.OuterClassVariable);
Console.WriteLine(this.InnerClassVariable);

elegance Demo

public static void Main()

ContainerClass.InnerClass nestedClassObj = new ContainerClass.InnerClass();


Question 98. What Is The Ouput Of The Following Program?

Answer :

the use of System;
namespace Nested

class ContainerClass

public ContainerClass()

Console.WriteLine("I am a field magnificence");

public magnificence InnerClass : ContainerClass

public InnerClass()

Console.WriteLine("I am an inner magnificence");

elegance DemoClass : ContainerClass.InnerClass

public DemoClass()

Console.WriteLine("I am a Demo class");

public static void Main()

DemoClass DC = new DemoClass();

Output:
I am a container elegance
I am an inner class
I am a Demo magnificence

The above application has used the standards of inheritance and nested lessons. The ContainerClass is on the top in the inheritance chain. The nested InnerClass derives from outer ContainerClass. Finally the DemoClass derives from nested InnerClass. As all of the three training are related via inheritance we've got the above output.

Question 99. What Is A Destructor?

Answer :

A Destructor has the equal call as the elegance with a tilde individual and is used to smash an instance of a category.

Question 100. Can A Class Have More Than 1 Destructor?

Answer :

No, a class could have best 1 destructor.

Question one zero one. Can Structs In C# Have Destructors?

Answer :

No, structs may have constructors however not destructors, best




CFG