[Obsolete]
public int Foo()
{…}
//or
[Obsolete(\"This is a message describing why this method is obsolete\")]
public int Foo()
{…}
24. What is a sealed class?
It is a class, which cannot be subclassed. It is a good practice to mark your classes as sealed, if you do not intend them to be subclassed.
25. How do you prevent a class from being inherited?
Mark it as sealed.
26. Can you inherit from multiple base classes in C#?
No. C# does not support multiple inheritance, so you cannot inherit from more than one base class. You can however, implement multiple interfaces.
27. What is an indexer in C#?
The indexers are usually known as smart arrays in C# community. Defining a C# indexer is much like defining properties. We can say that an indexer is a member that enables an object to be indexed in the same way as an array.
class MyClass
{
private string []data = new string[5];
public string this [int index]
{
get
{
return data[index];
}
set
{
data[index] = value;
}
}
}
Where the modifier can be private, public, protected or internal. The return type can be any valid C# types. The ‘this’ is a special keyword in C# to indicate the object of the current class. The formal-argument-list specifies the parameters of the indexer.
28. What is the use of fixed statement?
The fixed statement sets a pointer to a managed variable and “pins” that variable during the execution of statement.
Without fixed, pointers to managed variables would be of little use since garbage collection could relocate the variables unpredictably. (In fact, the C# compiler will not allow you to set a pointer to a managed variable except in a fixed statement.)
Class A
{
public int i;
}
A objA = new A; // A is a .net managed type
fixed(int *pt = &objA.i) // use fixed while using pointers with managed
// variables
{
*pt=45; // in this block use the pointer the way u want
}
29. What is the order of destructors called in a polymorphism hierarchy?
Destructors are called in reverse order of constructors. First destructor of most derived class is called followed by its parent’s destructor and so on till the topmost class in the hierarchy.
You don’t have control over when the first destructor will be called, since it is determined by the garbage collector. Sometime after the object goes out of scope GC calls the destructor, then its parent’s destructor and so on.
When a program terminates definitely all object’s destructors are called.
30. What is a virtual method?
Ans.In C#, virtual keyword can be used to mark a property or method to make it overrideable. Such methods/properties are called virtual methods/properties.By default, methods and properties in C# are non-virtual.
31. Is it possible to Override Private Virtual methods?
No, First of all you cannot declare a method as ‘private virtual’.
32. Can I call a virtual method from a constructor/destructor?
Yes, but it’s generally not a good idea. The mechanics of object construction in .NET are quite different from C++, and this affects virtual method calls in constructors.C++ constructs objects from base to derived, so when the base constructor is executing the object is effectively a base object, and virtual method calls are routed to the base class implementation. By contrast, in .NET the derived constructor is executed first, which means the object is always a derived object and virtual method calls are always routed to the derived implementation. (Note that the C# compiler inserts a call to the base class constructor at the start of the derived constructor, thus preserving standard OO semantics by creating the illusion that the base constructor is executed first.)The same issue arises when calling virtual methods from C# destructors. A virtual method call in a base destructor will be routed to the derived implementation.
33. How do I declare a pure virtual function in C#?
Use the abstract modifier on the method. The class must also be marked as abstract (naturally). Note that abstract methods cannot have an implementation (unlike pure virtual C++ methods).
34. Are all methods virtual in C#?
No. Like C++, methods are non-virtual by default, but can be marked as virtual.
35. What is the difference between shadow and override?
When you define a class that inherits from a base class, you sometimes want to redefine one or more of the base class elements in the derived class. Shadowing and overriding are both available for this purpose.
Comparison
It is easy to confuse shadowing with overriding. Both are used when a derived class inherits from a base class, and both redefine one declared element with another. But there are significant differences between the two.The following table compares shadowing with overriding.
Point of comparison Shadowing OverridingPurposeShadowing
Protecting against a subsequent base class modification that introduces a member you have already defined in your derived classAchieving polymorphism by defining a different implementation of a procedure or property with the same calling sequence1Redefined elementShadowing
Any declared element typeOnly a procedure (Function, Sub, or Operator) or propertyRedefining elementShadowing
Any declared element typeOnly a procedure or property with the identical calling sequence1Access level of redefining elementShadowing
Any access levelCannot change access level of overridden elementReadability and writability of redefining elementShadowing
Any combinationCannot change readability or writability of overridden propertyControl over redefiningShadowing
Base class element cannot enforce or prohibit shadowingBase class element can specify MustOverride, NotOverridable, or OverridableKeyword usageShadowing
Shadows recommended in derived class; Shadows assumed if neither Shadows nor Overrides specified2Overridable or MustOverride required in base class; Overrides required in derived classInheritance of redefining element by classes deriving from your derived classShadowing
Shadowing element inherited by further derived classes; shadowed element still hidden3Overriding element inherited by further derived classes; overridden element still overridden
1 The calling sequence consists of the element type (Function, Sub, Operator, or Property), name, parameter list, and return type. You cannot override a procedure with a property, or the other way around. You cannot override one kind of procedure (Function, Sub, or Operator) with another kind.
2 If you do not specify either Shadows or Overrides, the compiler issues a warning message to help you be sure which kind of redefinition you want to use. If you ignore the warning, the shadowing mechanism is used.
3 If the shadowing element is inaccessible in a further derived class, shadowing is not inherited. For example, if you declare the shadowing element as Private, a class deriving from your derived class inherits the original element instead of the shadowing element.
36. Should I make my destructor virtual?
C# destructor is really just an override of the System.Object Finalize method, and so is virtual by definition
37. Are C# destructors the same as C++ destructors?
No. They look the same but they are very different. The C# destructor syntax (with the familiar ~ character) is just syntactic sugar for an override of the System.Object Finalize method. This Finalize method is called by the garbage collector when it determines that an object is no longer referenced, before it frees the memory associated with the object. So far this sounds like a C++ destructor. The difference is that the garbage collector makes no guarantees about when this procedure happens. Indeed, the algorithm employed by the CLR garbage collector means that it may be a long time after the application has finished with the object. This lack of certainty is often termed ‘non-deterministic finalization’, and it means that C# destructors are not suitable for releasing scarce resources such as database connections, file handles etc.To achieve deterministic destruction, a class must offer a method to be used for the purpose. The standard approach is for the class to implement the IDisposable interface. The user of the object must call the Dispose() method when it has finished with the object. C# offers the ‘using’ construct to make this easier.
38. Are C# constructors the same as C++ constructors?
Very similar, but there are some significant differences. First, C# supports constructor chaining. This means one constructor can call another:
class Person
{
public Person( string name, int age ) { … }
public Person( string name ) : this( name, 0 ) {}
public Person() : this( "", 0 ) {}
}
Another difference is that virtual method calls within a constructor are routed to the most derived implementationError handling is also somewhat different. If an exception occurs during construction of a C# object, the destuctor (finalizer) will still be called. This is unlike C++ where the destructor is not called if construction is not completed.Finally, C# has static constructors. The static constructor for a class runs before the first instance of the class is created.Also note that (like C++) some C# developers prefer the factory method pattern over constructors.
39. Can you declare a C++ type destructor in C# like ~MyClass()?
Yes, but what’s the point, since it will call Finalize(), and Finalize() has no guarantees when the memory will be cleaned up, plus, it introduces additional load on the garbage collector. The only time the finalizer should be implemented, is when you’re dealing with unmanaged code.
40. What are the fundamental differences between value types and reference types?
C# divides types into two categories – value types and reference types. Most of the intrinsic types (e.g. int, char) are value types. Structs are also value types. Reference types include classes, arrays and strings. The basic idea is straightforward – an instance of a value type represents the actual data, whereas an instance of a reference type represents a pointer or reference to the data.The most confusing aspect 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 decision.For example, in C++ we can do this:
int x1 = 3; // x1 is a value on the stack
int *x2 = new int(3) // x2 is a pointer to a value on the heapbut in C# there is no control:int x1 = 3; // x1 is a value on the stack
int x2 = new int();
x2 = 3; // x2 is also a value on the stack!
41.How do you handle errors in VB.NET and C#?
C# and VB.NET use structured error handling (unlike VB6 and earlier versions where error handling was implemented using Goto statement). Error handling in both VB.NET and C# is implemented using Try..Catch..Finally construct (C# uses lower case construct – try…catch…finally).
42. What is the purpose of the finally block?
The code in finally block is guaranteed to run, irrespective of whether an error occurs or not. Critical portions of code, for example release of file handles or database connections, should be placed in the finally block.
43. Can I use exceptions in C#?
Yes, in fact exceptions are the recommended error-handling mechanism in C# (and in .NET in general). Most of the .NET framework classes use exceptions to signal errors.
44. Why is it a bad idea to throw your own exceptions?
Well, if at that point you know that an error has occurred, then why not write the proper code to handle that error instead of passing a new Exception object to the catch block? Throwing your own exceptions signifies some design flaws in the project.
45. What’s the C# syntax to catch any possible exception?
A catch block that catches the exception of type System. Exception. You can also omit the parameter data type in this case and just write catch {}
46. How to declare a two-dimensional array in C#?
Syntax for Two Dimensional Array in C Sharp is int[,] ArrayName;
47.How can you sort the elements of the array in descending order?
Using Array.Sort() and Array.Reverse() methods.
int[] arr = new int[3];
arr[0] = 4;
arr[1] = 1;
arr[2] = 5;
Array.Sort(arr);
Array.Reverse(arr);
48. What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?
The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element’s object, resulting in a different, yet identacle object.
49. Structs are largely redundant in C++.Why does C# have them?
In C++, a struct and a class are pretty much the same thing. The only difference is the default visibility level (public for structs, private for classes). However, in C# structs and classes are very different. In C#, structs are value types (instances stored directly on the stack, or inline within heap-based objects), whereas classes are reference types (instances stored on the heap, accessed indirectly via a reference). Also structs cannot inherit from structs or classes, though they can implement interfaces. Structs cannot have destructors. A C# struct is much more like a C struct than a C++ struct.
50. How does one compare strings in C#?
In the past, you had to call .ToString() on the strings when using the == or != operators to compare the strings’ values. That will still work, but the C# compiler now automatically compares the values instead of the references when the == or != operators are used on string types. If you actually do want to compare references, it can be done as follows: if ((object) str1 == (object) str2) { … } Here’s an example showing how string compares work:
using System;
public class StringTest
{
public static void Main(string[] args)
{
Object nullObj = null; Object realObj = new StringTest();
int i = 10;
Console.WriteLine(\"Null Object is [\" + nullObj + \"]\n\"
+ \"Real Object is [\" + realObj + \"]\n\"
+ \"i is [\" + i + \"]\n\");
// Show string equality operators
string str1 = \"foo\";
string str2 = \"bar\";
string str3 = \"bar\";
Console.WriteLine(\"{0} == {1} ? {2}\", str1, str2, str1 == str2 );
Console.WriteLine(\"{0} == {1} ? {2}\", str2, str3, str2 == str3 );
}
}Output:Null Object is []
Real Object is [StringTest]
i is [10]
foo == bar ? False
bar == bar ? True
51. Where we can use DLL made in C#.Net?
Supporting .Net, because DLL made in C#.Net semi compiled version. It’s not a com object. It is used only in .Net Framework As it is to be compiled at runtime to byte code.
52. If A.equals(B) is true then A.getHashcode & B.gethashcode must always return same hash code.
The answer is False because it is given that A.equals(B) returns true i.e. objects are equal and now its hashCode is asked which is always independent of the fact that whether objects are equal or not. So, GetHashCode for both of the objects returns different value.
53.Is it possible to debug the classes written in other .Net languages in a C# project?
It is definitely possible to debug other .Net languages code in a C# project. As everyone knows .net can combine code written in several .net languages into one single assembly. Same is true with debugging.
54. Does C# has its own class library?
Not exactly. The .NET Framework has a comprehensive class library, which C# can make use of. C# does not have its own class library.
55. IS it possible to have different access modifiers on the get/set methods of a property?
No. The access modifier on a property applies to both its get and set accessors. What you need to do if you want them to be different is make the property read-only (by only providing a get accessor) and create a private/internal set method that is separate from the property.
56. Is it possible to restrict the scope of a field/method of a class to the classes in the same namespace?
There is no way to restrict to a namespace. Namespaces are never units of protection. But if you’re using assemblies, you can use the ‘internal’ access modifier to restrict access to only within the assembly.
57. Is there an equivalent of exit() or quiting a C#.NET application?
Yes, you can use System.Environment.Exit(int exitCode) to exit the application or Application.Exit() if it’s a Windows Forms app.
58. What optimization does the C# compiler perform when you use the /optimize+compiler option?
The following is a response from a developer on the C# compiler team: We get rid of unused locals (i.e., locals that are never read, even if assigned). We get rid of unreachable code. We get rid of try-catch with an empty try. We get rid of try-finally with an empty try. We get rid of try-finally with an empty finally. We optimize branches over branches: gotoif A, lab1 goto lab2: lab1: turns into: gotoif !A, lab2 lab1: We optimize branches to ret, branches to next instruction, and branches to branches.
59. Does C# support multiple inheritance?
No, use interfaces instead.
60. IS goto statement supported in C#?How about Java?
Gotos are supported in C# to the fullest. In Java goto is a reserved keyword that provides absolutely no functionality.
61. What happens when you encounter a continue statement inside for loop?
The code for the rest of the loop is ignored, the control is transferred back to the beginning of the loop.
62. Write one code example for compile time binding and one for run time binding?what is early/late binding? An object is early bound when it is assigned to a variable declared to be of a specific object type . Early bound objects allow the compiler to allocate memory and perform other optimizations before an application executes.
‘ Create a variable to hold a new object.
Dim FS As FileStream
‘ Assign a new object to the variable.
FS = New FileStream("C:\tmp.txt", FileMode.Open)
By contrast, an object is late bound when it is assigned to a variable declared to be of type Object. Objects of this type can hold references to any object, but lack many of the advantages of early-bound objects.
Dim xlApp As Object
xlApp = CreateObject("Excel.Application")
Good. Quite informative.
Regarding Q 55, in C# 2.0 we have the feature to have different accessibility for get/ set, though with some rules to be followed. The feature is called Asymmetric Accessor Accessibility. Refer:
http://msdn2.microsoft.com/en-us/library/75e8y5dd(VS.80).aspx
can u send .NET objective type Questions. please
quite good for fast revision of .NET interviewS
Questions are pretty good, but most of them can be found across the net.
It would be better to add some real time question / real time senarios based once.
Any ways good work.
good
very nice article abt interview questions
plz send me where exactly we use abstact and interface
Very Good article …But some articles are not covered correctly..
Hi Ripalsoni,
I read Your Interview Qns $ Ans.Really good preparation.Thanks for You.
Thanks $ Regards
Pandian
Good article. Got lot knowledge
very nice
Great for answering hard questions for fianls.
thnxs for providing such nice stuff…..once again thnk U
dese were reely useful…thnx for providin dem
This is very informative
Thanks
Thanks a lot!
Have a good life to you for providing such kind of materials. Thanks ons again…….
Good collection .. with nice explanation
To learn more about OOAD and design patterns see the blog http://www.patnys.com
I am curious about #52. I am coming from a java background here, but the contract of a hashcode is that if a.getHashCode() equals b.getHashCode(), a and b are not necessarily equal; they could be…and they could not be; however, if you know for a fact that a and b are equal, then their hashcodes MUST be equal.
I would think this holds true in c#. Can someone help me out here as I’m having a little difficulty processing what #52 is saying. For now, I believe the answer to be wrong, but I’ll do some research on it.
An example would be fabulous.
Very useful….liked this..
Good one!!!!!!!!!!
Excellent…..
Fantastic interview review and quiet informative
good quite logical pointed answer
10/10
more information i got. best one…………………
Excellent.
Good article, but author really needs to work on his english
hi,
This is an excellent set of questions for interview preparetion. Very good explanation as well.
thanks.
vary well all interview ques…
Good Work. Thank you very much for the good stuff provided.
Very nice work . Keep it up 🙂
These are nice questions. eXtendCode team (www.extendcode.com) appreciate these questions
Nice collection buddy.
Really its good and helped for me alot……..thank u
Really good question answer to improve basic knowledge of .net learner.
I agree but some are really interesting one.
Thank you for giving me a light to asp.net
well ,that is something very usefull material for me.thanks
it is very important website for fresher.
very well….material is usefull for all
Nice collection and good try to collect some sensible question.
If you want to know more questions on C# please vist this site
C# Interview Questions
Too Good 🙂
VERY GOOD CONTENT……I WANT SOME MORE QUESTIONS AND ANSWERS RELATED TO .NET…..THANKS
Nice Collections of C# Interview question. It really helpful for beginner as well as developer. Check following link too, It is also having a nice collection on C# interview question…
http://www.mindstick.com/Interviewer/QuestionPage.aspx?topicid=1&topic=C%23
Simply WOW, keep posting such more questions on other tech. i.e. SQL Server or WCF or MVC or Web Service or LINQ etc.
thanks for the help.. the article really helped me a lot.. being enrolled in a .net interview course at http://www.wiziq.com/course/46-INTERVIEW-PREPARATION-COURSE-BY-SHIVPRASAD-KOIRALA i was looking for such information available online//
very very helpful
Thanks for help
Really i enjoyed with interview questions Thank you
No comment from my side
Very good post. I will be experiencing a few of these issues as well.
.
Great collections of questions you are having for similar kind of C# interview questions you can refer this link
c# interview questions
@ http://skillgun.com
Sharing the Dot Net Material for Freshers,
Link as,
dotnettrainingchennai
Thanks to Sharing the Dot Net Material for Freshers,
Link as, dotnettrainingchennai