C# interview

2,819 views

Published on

Basic Interview Related Question and Answers!!

Published in: Technology, Business
1 Comment
7 Likes
Statistics
Notes
  • Great list. We are inviting Java Developers like you to help the other developers on http://www.gofaqs.com and get paid $ 1.00 per answer
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Views
Total views
2,819
On SlideShare
0
From Embeds
0
Number of Embeds
4
Actions
Shares
0
Downloads
638
Comments
1
Likes
7
Embeds 0
No embeds

No notes for slide

C# interview

  1. 1. InterviewQuestionsC# .NET & ASP .NET
  2. 2. Polymorphism Polymorphism means one interface and many forms.Polymorphism is a characteristics of being able to assign adifferent meaning or usage to something in differentcontexts specifically to allow an entity such as a variable, afunction or an object to have more than one form. There are two types of polymorphism Compile Time – function or operator overloading Runtime – inheritance or virtual functions. EXAMPLE - Overriding
  3. 3. Abstract method It doesn’t provide the implementationand forces the derived class to overridethe method.
  4. 4. Virtual Method It has implementation and provide thederived class with the option to override it.
  5. 5. Object Object is anything that is identifiable as singlematerial item. Object is an instance of a class, it contains realvalues instead of variables. For example, letscreate an instance of class Emp called “Siva”. Emp Siva = New Emp(); Now we can access all methods in the class “Emp” via object “Siva” as shown below. Siva.setName(“Hi”);
  6. 6. Class It is the generic definition of what an object is a template. They keyword class in c# indicates that we are going todefine a new class (type of object) class is the generic definition of what an object is. A Class describes all the attributes of object, as well as themethods that implements the behavior of member object. That means, class is a template of an object. Easy way tounderstand a class is to look at an example .
  7. 7. Static method It is possible to declare a method as staticprovided that they don’t attempt toaccess any instance data or otherinstance methods.
  8. 8. Inheritance It provides a convenient way to reuseexisting fully tested code in differentcontext thereby saving lot of coding. Inheritance of classes in C# is alwaysimplementation Inheritance.
  9. 9. Virtual Keyword This keyword indicatesthat a member can beoverridden in a child class.It can be applied tomethods, properties,indexes and events.
  10. 10. Abstract class Abstract class is a class that can not be instantiated, it exists extensivelyfor inheritance and it must be inherited. There are scenarios in which it isuseful to define classes that is not intended to instantiate; because suchclasses normally are used as base-classes in inheritance hierarchies, wecall such classes abstract classes. Abstract classes cannot be used to instantiate objects; becauseabstract classes are incomplete, it may contain only definition of theproperties or methods and derived classes that inherit this implements itsproperties or methods. Static, Value Types & interface doesnt support abstract modifiers. Staticmembers cannot be abstract. Classes with abstract member must alsobe abstract.
  11. 11. Sealed Modifiers Sealed types cannot be inherited and areconcrete. Sealed modifiers can also be applied toinstance methods, properties, events and indexes.It can’t be applied to static members Sealed members are allowed in sealed and nonsealed classes. If a class is defined as Sealed it cannot beinherited in derived class. See the above example.
  12. 12. Interface An interface is a contract & defines therequisite behavior of generalization of types. An interface mandates a set of behavior, butnot the implementation. Interface must beinherited. We cant create an instance of aninterface. An interface is an array of related function thatmust be implemented in derived type.Members of an interface are implicitly public &abstract. An interface can inherit from another interface.
  13. 13. Pure Virtual FunctionIt is a function that must be overridden inderived class and need not be defined. Avirtual function is declared to be “pure”using the curious “=0”. Syntax:Class Base {Public:void f1() // not virtualVirtual void f2(); // virtual but not pureVirtual void f3() = 0; // pure virtual function};
  14. 14. Access Modifiers in C#? There are five access modifier Public Private Protected Internal Protected internal
  15. 15. Public Access Modifier When a method or attribute is defined asPublic, it can be accessed from any code inproject. The public is a keyword and type members ie.We can declare a class or its members(methods) as public. There are no restrictionson accessing public members.
  16. 16. Private Access Modifier When a method or attribute is defines as private, it can beaccessed by any code within the containing type only. We can’t explicitly declare a class as private, however if donot specify any access modifier to the class, its scope willbe assumed as private. Private access is the leastpermissive access level of all access modifiers Private members are accessible only with in the body of theclass or the struct in which they are declared. This is thedefault access modifier for the class declaration.
  17. 17. Protected Access Modifier When an attribute and methods are definedas protected, it can be accessed by anymethod in inherited classes & any methodwithin the same class. The protected accessmodifier can’t be applied to class andinterfaces. Methods and fields in a interfacecan’t be declared protected.
  18. 18. Internal Access Modifier If an attribute or method is defined asInternal , Access is restricted to classeswithin the current project assembly.
  19. 19. Protected Internal AccessModifier If an attribute or method is defined asProtected Internal , Access is restricted toclasses within the current projectassembly and types derived from thecontaining class.
  20. 20. References types in C# Here emp2 has an object instance ofEmployee Class . But emp1 object is set asemp2. What this means is that object emp2 isrefereed in emp1 and not that emp2 iscopied into emp1. When a change is made inemp2 object, corresponding changes can beseen in emp1 object.
  21. 21. Overloading in C#? When methods are created with same name, but with different signature its calledoverloading. We have types of overloading in C#: Constructor Function or method Operator
  22. 22. Constructor Overloading In Constructor overloading, n number ofconstructors can be created for sameclass. But the signatures of eachconstructor should vary.
  23. 23. Function/Method Overloading Method overloading allows us to write different version ofthe same method in a class or derived class. Compilerautomatically select the most appropriate method basedon the parameter supplied. Method overloading occurswhen a class contains two methods with the same name,but different signatures. In Function overloading, n number of functions can becreated for same class. But the signatures of each functionshould vary Note - You cant have a overload method with same number parameters but differentreturn type. In order to create overload method, the return type must be the same andparameter type must be different or different in numbers.
  24. 24. Operator Overloading We had seen function overloading in the previous eg: For operatorOverloading , we will have look at the example below. We define aclass rectangle with two operator overloading methods.Let us call the operator overloaded functions from the methodbelow. When first if condition is triggered, first overloaded functionin the rectangle class will be triggered. When second if condition istriggered, second overloaded function in the rectangle class willbe triggered.
  25. 25. Method Overriding Method overriding is a feature that allows toinvoke methods that have the samesignatures and that belong to different classesin the same hierarchy of inheritance using thebase class reference. In C# it is done usingkeywords, virtual and overrides.
  26. 26. Encapsulation Data encapsulation is defined as the processof data hiding the important fields from theend user. Data Hiding is nothing but restricting outsideaccess of a class members using accessmodifiers such as private , protected andinternal etc.,
  27. 27. What is an Array? An array is a collection of related instanceeither value or reference types. Array possesan immutable structure in which the numberof dimensions and size of the array are fixedat instantiation. C# supports, Single Dimension – it is sometimes called vector array consists of single row. Multi Dimension Array – are rectangular and consists of rows and columns. Jagged array – also consists of rows and columns but irregular shaped like row1 has3 column and row 2 has 5 column.
  28. 28. Array List ArrayList is a dynamicarray. Elements can beadded and removedfrom an array list at theruntime. In thiselements are notautomatically sorted. The bit array collectionis a composite of bitvalues. It stores 1 or 0where 1 is true and 0 isfalse. This collectionprovides an efficientmeans of storing andretrieving bit values.Bit Array
  29. 29. Hash Table A hashTable is a collection of key valuepairs. Entries in this are instance ofDictionaryEntry type. It implementsIdictionary, Iserilizable, Ideserializablecallback interface.
  30. 30. Queue This is a collection thatabstracts FIFO (First InFirst Out) datastructure. The initialcapacity is 32elements. It is ideal formessagingcomponents. This is a collectionthat abstracts LIFO(Last In First Out)data structure inwhich initialcapacity is 32.Stack
  31. 31. Early Binding and late binding Calling a non virtual method, decided ata compile time is known as early binding. Calling a virtual method (purepolymorphism), decided at a runtime isknown as late binding.
  32. 32. SortedList This is a collection and it is a combinationof key/value entries and an ArrayListcollection. Where the collection is sortedby key.
  33. 33. Delegates A delegate in C# allows you to pass method ofone class to objects of other class that can callthese methods. It is a type safe function pointer. It is a type thatholds reference of a method. A delegate may beused to call a method asynchronously. public delegate void OperationDelegate();
  34. 34. DelegatesSingle A delegate is called single castdelegate if it invokes a singlemethod. In other words we cansay that singlecast delegatesrefer to a single method withmatching signature. Single castdelegate derive from theSystem.Delegate class.Multicast It is a delegate thatholds reference of morethan one method.Multicast Delegatesmust have a return typeof void, else there is aruntime exception.
  35. 35. SingleCast Delegate In the code snippet I have declared a singledelegate which takes two integer type asarguments and returns an integer as return type.delegate int mySingleCastDelegate(int iFirstargument, int iSecondArgument); At runtime I have created a delegate variable assingleCastMaxNumberDelegate of typemySingleCastDelegate. Using the delegatevariable, I can point to any method that has thematching signature. In the example the method myMaxFunction hasthe matching signature with the delegate variable.So using the new keyword I have referenced thedelegate variable to the myMaxFunctionf:mySingleCastDelegate singleCastMaxNumberDelegate = newmySingleCastDelegate(clsSingleCastDelegate.myMaxFunction); Now I can call the functionmyMaxFunction by passingrequired parametersthrough the delegate.int iMaxNumberResult = singleCastMaxNumberDelegate(10, 20);
  36. 36. MultiCast Delegate There are two functions declared, myAddtionfunction andmyMaxFunction. Both of theses functions take two integertype as parameters and return void. I have created threedelegate variables of type MultiCast Delegate, out of whichmyDelegate assigned with null value where as the other twodelegates referenced to each of two functions. I have used the Combine method of system.delegate tocombine the two delegate variables. System.Delegate provides another method, remove, whichcan be used to remove the specific delegate from the list.Here the remove function is being used to remove themyMultiCastDelegateMaxNumber function from myDelegatelist When we run the above code snipet, then we get thefollowing result:
  37. 37. Asynchronous call and how it canbe implemented in delegates? The Asynchronous calls wait for a methodbefore the program flow is resumed tocomplete its task. In an asynchronous call,the program flow continues while themethod is executes.
  38. 38. Reflection It is the ability to find the information about typescontained in an assembly at runtime. All .NET compilers produce metadata about thetypes defined in the modules they produce. Thismetadata is packaged along with the module(modules in turn are packaged together inassemblies), and can be accessed by amechanism called reflection.
  39. 39. Garbage Collection Garbage collection is a mechanism that allowsthe computer to detect when an object can nolonger be accessed. It then automatically releasesthe memory used by that object (as well as callinga clean-up routine, called a "finalizer," which iswritten by the user). Some garbage collectors, likethe one used by .NET, compact memory andtherefore decrease your programs working set.
  40. 40. Assembly An assembly may be an exe, a dll, an applicationhaving an entry point, or a library. It may consist ofone or more files. An assembly maybe shared(public)or private. The assembly, overall comprises of 3entities: IL, Manifest, Metadata. Metadata describesIL, whereas Manifest describes the assembly. Anassembly may be created by building the class(the.vb or .cs file), thereby producing its DLL.
  41. 41. How to Produce Assembly? The simplest way to produce an assembly is directly from a .NETcompiler. For example, the following C# program:public class CTest{public CTest() { System.Console.WriteLine( "Hello from CTest" ); }}can be compiled into a library assembly (dll) like this:csc /t:library ctest.cs You can then view the contents of the assembly by running the "ILDisassembler" tool that comes with the .NET SDK. Alternatively you can compile your source into modules, and thencombine the modules into an assembly using the assembly linker(al.exe). For the C# compiler, the /target:module switch is used togenerate a module instead of an assembly.
  42. 42. Global Assembly Cache A shared assembly has version constraints.It is stored in the Global Assembly Cache(GAC). GAC is a repository of shared assembliesmaintained by the .NET runtime. Theshared assemblies may be used by manyapplications. To make an assembly ashared assembly, it has to be stronglynamed.
  43. 43. Satellite assembly When you write a multilingual or multi-cultural application in .NET, and want todistribute the core application separatelyfrom the localized modules, the localizedassemblies that modify the coreapplication are called satellite assemblies.
  44. 44. Using Statement in C# Using statement is used to work with an object in C#that inherits Idisposable interface. Idisposable interface has one public method calleddispose that us used to dispose off the object. Whenwe use the using statement, we don’t need toexplicitly dispose the object in the code, the usingstatement takes care of it. Using statement makes the code more readable andcompact.
  45. 45. C# Preprocessor Directives#region , #endregion :- Used to marksections of code that can be collapsed.#define , #undef :-Used to define andundefine conditional compilation symbols.#if , #elif , #else , #endif :- These are used toconditionally skip sections of source code.
  46. 46. Value Type & Reference TypeValue Type As name suggest Value Type stores“value” directly. out keyword is used for passing avariable for output purpose. It hassame concept as ref keyword, butpassing a ref parameter needsvariable to be initialized while outparameter is passed without initialized.It is useful when we want to returnmore than one value from themethod.Reference Type As name suggest Reference Typestores “reference” to the value. Passing variable by value is thedefault. However, we can force thevalue parameter to be passed byreference. Note: variable “must” beinitialized before it is passed into amethod.
  47. 47. Boxing & UnboxingBoxing It means converting valuetype to reference type. Eg: int I = 20;string s = I.ToSting();Un-Boxing It means converting referencetype to value type. Eg: int I = 20; string s = I.ToString();//Box the int int J = Convert.ToInt32(s); //UnBoxit back to an intNote: Performance Overheads due to boxing and unboxing asthe boxing makes a copy of value type from stack and place itinside an object of type System.Object in the heap
  48. 48. String & string in C#String String is an class(System.String) String is an referencetype (class)string string is an alias name of Stringclass that is created byMicrosoft string is an value type(datatype) string is a C# keyword. string is a compiler shortcut forSystem.String classNote: As per above points when we use string keyword, it reachesthe System.String class and then process accordingly, So we cansay that both String and string are same
  49. 49. ILDASM The ILDASM stands for Intermediate LanguageDisassembler. This is a de-compiler which helps to getthe source code from the assembly. This ILDASM converts an assembly to instructions fromwhich source code can be obtained. The ILDASM can analyze the .dll or .exe files andconverts into human readable form. This is used toexamine assemblies and understanding the assemblycapability.
  50. 50. Debug.Write & Trace.Write The Debug.Write will work while the application is inboth Debug Mode and Release Mode. This isnormally used while you are going to debug aproject. This will not be work when you will definesome debug points to your project. But the Trace.write will work while the application isonly in Release Mode. This is used in released versionof an application. This will compiled when you willdefine debug points in your project.
  51. 51. Exception Handler An exception is an abnormal event orerror condition that exists in the technicalexecution of a particular statement thatoccurs during the program execution.
  52. 52. String Vs String Builder String – once the string object is created,its length and content cannot bemodified. It is slower. StringBuilder – even after object iscreated, it can be able to modify lengthand content. It is faster.
  53. 53. Illustrate Server.Transfer &Response.Redirect? Server.Transfer, transfers the control of a web page, postinga form data, while Response.Redirect simply redirects apage to another page, it can not post a form data toanother page. Server.Transfer is more efficient over theResponse.Redirect, because Response.Redirect causes around trip to server as the page is processed once againon the client & a request is made to server there after. But the browser URL is not changed in case ofServer.Transfer i.e., browser history is not modified in using it.
  54. 54. Illustrate Server.Transfer &Response.Redirect? Server.Transfer, transfers the control of a web page, postinga form data, while Response.Redirect simply redirects apage to another page, it can not post a form data toanother page. Server.Transfer is more efficient over theResponse.Redirect, because Response.Redirect causes around trip to server as the page is processed once againon the client & a request is made to server there after. But the browser URL is not changed in case ofserver.transfer i.e., browser history is not modified in using it.

×