2016-06-16

C Sharp interview question answers

1. Define protected class-level variable in C#.NET.

Answer: It can be inherited by the classes in the same namespace.

2. What is an abstract class?

Answer: • We can't create the instance of an abstract class, because abstract classes are incomplete. • Abstract modifier doesn't supported by interface, Values type and static types. • We can declare class as abstract by using abstract keyword in beggining of the class definition. • Abstract class provides similar definition of base class which can be shared by multiple derived classes. • Abstract class may define abstract methods by using the abstract keyword before the method definition. • Abstract methods have no implementation, only they can be implemented in the derived class. For Example: public abstract class Demo { public abstract void DoWork(int a); }

3. How is method overriding different from method overloading?

Answer: When overriding a method, you change the behavior of the method for the derived class. Overloading a method simply involves having another method with the same name within the class.

4. What are delegates and why are they required?

Answer: The delegates in .NET are like the pointers to the functions in C/C++. The difference is that these are type safe unlike the once in C/C++. There are situations where in a programmer or an application needs to perform an action on a particular event. Eg: Some user action like click, text change, etc. So when these actions are performed by the user, the delegates invoke the respective functions.

5. What is difference between constants, readonly and, static ?

Answer: Constants: The value can’t be changed. Read-only: The value will be initialized only once from the constructor of the class. Static: Value can be initialized once.

6. What Is an Exception?

Answer: When we write a program, we describe step-by-step what the computer must do (at least in imperative programming; in the functional programming things look a bit different) and in most of the cases we rely that the program will execute normally. Indeed, most of the time, programs are following this normal pattern, but there are some exceptions. Let’s say we want to read a file and display its contents on the screen. Let’s assume the file is located on a remote server and during the process of reading it, the connection goes down. The file then will be only partially loaded. The program will not be able to execute normally and show file’s contents on the screen. In this case, we have an exception from the normal (and correct) program execution and this exception must be reported to the user and/or the administrator.

7. What is the difference between compile time polymorphism and run time polymorphism?

Answer: Compile time PolymorphismRun time Polymorphism Run time Polymorphism also known as method overriding. Method overriding means having two or more methods with the same name , same signature but with different implementation.

8. Out of Windows Authentication and SQL Server authentication, which one is trusted?

Answer: Windows Authentication is trusted because the username and password are checked with the Active Directory

9. Describe Anonymous functions in detail.

Answer: Ans: Anonymous means no name. An anonymous function is, an unnamed block of code that is passed to a delegate constructor. One advantage of using an anonymous function is that there is no need to declare a separate method whose only purpose is to be passed to a delegate. An anonymous method is created by following the keyword delegate with a block of code. Example: using System; namespace Test { delegate void AnonymousDemo(); class Demo { static void Main() { AnonymousDemo DelObj = delegate { // This is the block of code passed to the delegate. Console.WriteLine("Hello anonymous method"); }; // notice the semicolon DelObj(); } } }

10. What is the difference between string keyword and System.String class?

Answer: String keyword is an alias for Syste.String class. Therefore, System.String and string keyword are the same, and you can use whichever naming convention you prefer. The String class provides many methods for safely creating, manipulating, and comparing strings.

11. What are attributes?

Answer: • Attributes describe a type, method, or property in a way that can be queried using a technique call reflection. • Attributes specify which security privileges a class requires. • Attributes provide a description, title, and copyright notice to explain an assembly. • Attribute types derive from the System. Attribute base class and are declared using <> or [] notation. • Visual studio automatically creates some standard attributes for your assembly when you create a project including title, description, company, guide and version. • Attribute can also declare requirements or capabilities.

12. What Is an Operator?and types of operator in C#?

Answer: Operators allow processing of primitive data types and objects. They take as an input one or more operands and return some value as a result. Operators in C# are special characters (such as "+", ".", "^", etc.) and they perform transformations on one, two or three operands. Examples of operators in C# are the signs for adding, subtracting, multiplication and division from math (+, -, *, /) and the operations they perform on the integers and the real numbers. Operators in C# Operators in C# can be separated in several different categories: - Arithmetic operators – they are used to perform simple mathematical operations. - Assignment operators – allow assigning values to variables. - Comparison operators – allow comparison of two literals and/or variables. - Logical operators – operators that work with Boolean data types and Boolean expressions. - Binary operators – used to perform operations on the binary representation of numerical data. - Type conversion operators – allow conversion of data from one type to another.

13. What is Managed code?

Answer: • Manage Code are the codes which require common language runtime for its execution. • Managed code target the services of the common language runtime in .Net framework. • Managed code must provide the metadata necessary for the runtime to provide services like memory management, cross-language integration, code access security, and automatic lifetime control of objects. • Managed code provides services like cross-language integration, code access security, memory management and automatic lifetime control of objects by supplying necessary metadata for runtime. • Codes executed by Microsoft intermediate language are Managed code.

14. Explain how to implement Delegates in C#.NET

Answer: Here is an implementation of a very simple delegate that accepts no parameters. public delegate void MyDelegate();// Declaration class MyClass { public static void MyFunc() { Console.WriteLine("MyFunc Called from a Delegate"); } public static void Main() { MyDelegate myDel = new MyDelegate(MyFunc); myDel(); } }

15. Is is possible to force garbage collector to run?

Answer: Yes, we can force garbage collector to run using System.GC.Collect().

16. What are the features of C#?

Answer: • C# is a powerful and simple programming language for writing applications. • Developers can easily build the web services through any language, on any platform across the internet. • C# is a hybrid of C++ and VB. • C# has many C++ features in the area expressions, operators and statements. • C# introduces improvement in boxing, unboxing, type safety, events, and versioning and garbage collections. • It reduces programming error in the code due to fewer lines of code. • C# has a key feature that can split up the implementation into logical pieces called region. • It support multiline comment feature.

17. What is the difference between an event and a delegate?

Answer: • Events are the reason of happening and delegates are the address of function. • In .Net, Delegates looks like an interface with a single method and you can make a call to it by delegate's instance. • By event's you can let other people know that something going on. • Events is declared by using ''event'' keyword whereas delegate is declared by using ''delegate'' keyword as below Public event <nameofth handler>; Public delegates <type> <delegatename>; • Adding a public multicast delegate field is same as adding a public event to a class.

18. How does .NET remoting work?

Answer: • .NET remoting is a process of sending messages through channels. • Standard channels in remoting are HTTP and TCP. • TCP is used for LANs only while HTTP can be used for LANs or WANs (internet). • Support can provided for many message serialization formats. Examples are SOAP (XML-based) and binary. • By default, the HTTP channel uses SOAP and the TCP channel uses binary. channela can use any serialization format. • There are two styles of remote access: 1) SingleCall. Every request from a client is serviced by a new object. The object is thrown away on completion of request. 2) Singleton. Single server object processed all request from clients.

19. How can you allow class to be inherited and prevent the method from being over-ridden?

Answer: Declare the class as public and make the methods sealed. The method declaration with a sealed modifier is called as a sealed method. The same method must also include the override modifier. With the use of sealed modifier, a derived class is prevented from futher overriding the method.

20. What are the different categories of inheritance?

Answer: In C# inheritance may be implemented in different combinations as illustrated in figure and they include: Inheritance in Object Oriented Programming is of four types: Single inheritance: Contains one base class and one derived class. Hierarchical inheritance: Contains one base class and multiple derived classes of the same base class. Multilevel inheritance: Contains a class derived from a derived class. Multiple inheritances: Contains several base classes and a derived class.

21. How can I produce an assembly?

Answer: An assembly can produce from a .Net compiler. For Example, the following C# program: public class CDemo { public CDemo() { System.Console.WriteLine( "Hello from CDemo" ); } } Can be compiled into a dll as: Csc/t:library cdemo.cs Now the contents of assembly can be view through opening the ''IL Disassembler'' tool of .Net SDK. Also compiling source into modules and then using assembly linker (al.exe) for combining them to generate assembly.

22. Explain serialization.

Answer: Serialization is a process of converting an object into a stream of bytes. .Net has 2 serializers namely XMLSerializer and SOAP/BINARY Serializer. Serialization is maily used in the concept of .Net Remoting.

23. What is Un-Managed Code?

Answer: • Code which is perfectly executed by operating system is known as un-managed code. • C, C++, VB 6.0 are examples of unmanaged code. • Un-managed code all the time dependent on computer architecture. • Un-managed code always compile to native code, so require compilation of code for different platform again and again. • Developers should take care of type safety, security, memory allocations.

24. What is the role of data provider?

Answer: The .NET data provider layer resides between the application and the database. Its task is to take care of all their interactions. The .NET Data provider can be demonstrated to be: SQL Server data provider OLEDB data provider ODBC Data Provider ADO.NET supports the following OLE DB Providers: - SQLOLEDB - Microsoft OLE DB Provider for SQL Server. - MSDAORA - Microsoft OLE DB Provider for Oracle. - Microsoft.Jet.OLEDB.4.0 - OLE DB Provider for Microsoft Jet.

25. What are partial classes?

Answer: • Derived classes focus more on important portions by splitting a class definition into multiple source files using partial classes. • In partial class code is hidden in a file named Form.Designer.vb or Form.Designer.cs. • Partial class files can be viewed by expending all files in solution explorer. • We can enhance and extend auto-generated code by using partial classes. • These multiple files get compiled into a single class during compilation.

26. How can you overload a method?

Answer: Different parameter data types, different number of parameters, different order of parameters.

27. How do I spawn a thread?

Answer: We need to create an instance of a System.Threading.Thread object and passing it an instance of a ThreadStart delegate that will be executed on the new thread. For example: class MyDemoThread { public MyDemoThread( string initData ) { m_data = initData; m_thread = new Thread( new ThreadStart(ThreadMain) ); m_thread.Start(); } // ThreadMain() is executed on the new thread. private void ThreadMain() { Console.WriteLine( m_data ); } public void WaitUntilFinished() { m_thread.Join(); private Thread m_thread; private string m_data; } In this case creating an instance of the MyDemoThread class is sufficient to spawn the thread and execute the MyDemoThread.ThreadMain() method: MyDemoThread t = new MyDemoThread( "Hello, world." ); t.WaitUntilFinished();

28. How Does the "switch-case" Statement Work?

Answer: The structure switch-case chooses which part of the programming code to execute based on the calculated value of a certain expression (most often of integer type). The format of the structure for choosing an option is as follows: switch (integer_selector) { case integer_value_1: statements; break; case integer_value_2: statements; break; // … default: statements; break; } The selector is an expression returning a resulting value that can be compared, like a number or string. The switch operator compares the result of the selector to every value listed in the case labels in the body of the switch structure. If a match is found in a case label, the corresponding structure is executed (simple or complex). If no match is found, the default statement is executed (when such exists). The value of the selector must be calculated before comparing it to the values inside the switch structure. The labels should not have repeating values, they must be unique. As it can be seen from the definition above, every case ends with the operator break, which ends the body of the switch structure. The C# compiler requires the word break at the end of each case-section containing code. If no code is found after a case-statement, the break can be omittedand the execution passes to the next case-statement and continues until it finds a break operator. After the default structure break is obligatory. It is not necessary for the default clause to be last, but it’s recommended to put it at the end, and not in the middle of the switch structure.

29. What are the connections supported in Microsoft SQL Server?

Answer: Windows Authentication SQL Server authentication

30. Advantages of CLR procedure over T-SQL procedure

Answer: • The use of the CLR procedure makes it possible to do the complex database operations without having an in-depth knowledge of T-SQL. • It also enables focusing the business layer towards the database in orderto increase the server performance by avoiding unnecessary server trips. • Also, with the help of the .NET Base Class Libraries, the complex logical operations can be effectively performed. • It deals with automatic garbage collection, memory management, exception handling, etc. due to which it is known as Managed Procedure. • The concepts of the OOP can also be applied. • It provides the ability to leverage the features of .NET Code Access Security (CAS) to prevent assemblies from performing certain operations.

31. What is a Destructor?

Answer: It is called just before an object is destroyed. It can be used to run clean-up code.You can't control when a destructor is called since object clean up by common language runtime.

32. Define Delegate.

Answer: Delegates are kind of similar to the function pointers. But they are secure and type-safe. A delegate instance encapsulates a static or an instance method. Declaring a delegate defines a reference type which can be used to encapsulate a method having a specific signature.

33. What is an internal modifier?

Answer: • Internal members can access only from within the same assembly (.dll). • We can declare a class as internal, its member as internal or its fields as internal. • Use internal keyword before the class declaration to create an internal class. • Internal type can't access from external program. • Classes defined within the current assembly can access internal classes.

34. What is boxing?

Answer: • When Value type is explicitly converted into reference type is called as boxing. • The reverse process is known as unboxing, when reference type is explicitly converted into value type. • In boxing process, the Values of variable is stored in Stack is converted in an object reference is stored in heap. • If the recipient reference type is equivalent to the unboxed type, then the value is copied to the heap. • Unboxing called the vice versa process of boxing.

35. What is Delegates?

Answer: Delegates are a type-safe, object-oriented implementation of function pointers and are used in many situations where a component needs to call back to the component that is using it.

36. What is the difference between private and public keyword?

Answer: Private : The private keyword is the default access level and most restrictive among all other access levels. It gives least permission to a type or type member. A private member is accessible only within the body of the class in which it is declared. Public : The public keyword is most liberal among all access levels, with no restrictions to access what so ever. A public member is accessible not only from within, but also from outside, and gives free access to any member declared within the body or outside the body.

37. What Is an Object?

Answer: We are going to introduce the concept object in the context of OOP. Software objects model real world objects or abstract concepts (which are also regarded as objects). Examples of real-world objects are people, cars, goods, purchases, etc. abstract objects are concepts in an object area, which we have to model and use in a computer program. Examples of abstract objects are the data structures stack, queue, list and tree. They are not going to be a subject in this chapter, but we are going to see them in details in the next chapters. In objects from the real world (as well as in the abstract objects) we can distinguish the following two groups of their characteristics: - States – these are the characteristics of the object which define it in a way and describe it in general or in a specific moment - Behavior – these are the specific distinctive actions, which can be done by the object. Let’s take for example an object from the real world – "dog". The states of the dog can be "name", "fur color" and "breed", and its behavior – "barking", "sitting" and "walking". Objects in OOP combine data and the means for their processing in one. They correspond to objects in real world and contain data and actions: - Data members – embedded in objects variables, which describe their states. - Methods – we have already considered them in details. They are a tool for building the objects.

38. Can you inherit private class-level variables?

Answer: Yes, they can be inherited but they are not accessible in the derived class, so it looks as if it is not inherited.

39. Difference between an interface and abstract class

Answer: In the interface all methods must be abstract; In the abstract class some methods can be concrete. In the interface no accessibility modifiers are allowed, which ispossible in abstract classes.

40. What are the different types of statements supported in C#?

Answer: C# supports several different kinds of statements are Block statements, Declaration statements, Expression statements, Selection statements, Iteration statements, Jump statements, Try catch statements, Checked and unchecked Lock statement.

41. Why are strings in C# immutable?

Answer: • When string values changes it means string is immutable, in this whenever we assign new value to string it occupies new memory reference for its new value by creating new string instance. • String is declared by using String Keyword. • Always use mutable string defined in System.Text.StringBuilder whenever its values will change. • Inefficient use of memory and garbage collection resulted by Immutable string.

42. Difference between the System.Array.CopyTo() and System.Array.Clone().

Answer: System.Array.CopyTo() performs a deep copy of the array System.Array.Clone() performs a shallow copy of the array

43. How does C#.NET Generics and C++ Templates compare?

Answer: C# generics and templates in C++ are more or less similar syntactically. • C# Generic types are strong typed. C++ Templates are loosely typed. • C# Generic types are instantiated at the runtime. C++ templates are instantiated at the compile time. • C# Generic types do not permit the type parameters to have default values. C++ templates do.

44. Why is an Object Pool required?

Answer: The request for the creation of an object is served by allocating an object from the pool. This reduces the overhead of creating and re-creating objects each time an object creation is required.

45. What are value types and reference types?

Answer: Value types are stored in the Stack. Examples : bool, byte, chat, decimal, double, enum , float, int, long, sbyte, short, strut, uint, ulong, ushort. Reference types are stored in the Heap. Examples : class, delegate, interface, object, string.

46. Describe multicast event handling with example.

Answer: Ans using System; namespace Test { // Declare a delegate type for an event. delegate void MyEventHandler(); // Declare a class that contains an event. class MyEvent { public event MyEventHandler SomeEvent; // This is called to fire the event. public void OnSomeEvent() { if (SomeEvent != null) SomeEvent(); } } class ButtonClass { public void Buttonhandler() { Console.WriteLine("Event received by button object"); } } class CheckBoxClass { public void Chkhandler() { Console.WriteLine("Event received by checkbox object"); } } class EventDemo { static void Handler() { Console.WriteLine("Event received by EventDemo"); } static void Main() { MyEvent evt = new MyEvent(); ButtonClass btnObj = new ButtonClass(); CheckBoxClass chkObj = new CheckBoxClass(); // Add handlers to the event list. evt.SomeEvent += Handler; evt.SomeEvent += btnObj.Buttonhandler; evt.SomeEvent += chkObj.Chkhandler; // Fire the event. evt.OnSomeEvent(); Console.WriteLine(); // Remove a handler. evt.SomeEvent -= btnObj.Buttonhandler; evt.OnSomeEvent(); } } } Output: Event received by EventDemo Event received by button object Event received by checkbox object Event received by EventDemo Event received by checkbox object Important points regarding event. Events can be specified in interfaces. Implementing classes must supply the event. Events can be specified as abstract An event can be specified as sealed. An event can be virtual.

47. How do you inherit derived class from a base class in C#.NET? Name the Top .NET class that everything is derived from.

Answer: By usingcolon and then the name of the base class.

48. Method overriding vs. overloading

Answer: Overloading means having a method with the same name within the class Through overriding, you change the method behavior for a derived class.

49. What are Extender provider components? Explain how to use an extender provider in the project.

Answer: An extender provider is a component that provides properties to other components. Implementing an extender provider: • Use the ProvidePropertyAttribute, which specifies the name of the property that an implementer of IExtenderProvider provides to other components, attribute to specify the property provided by your extender provider. • Implement the provided property. • Track which controls receive your provided property. • Implement the IExtenderProvider, which defines the interface for extending properties to other components in a containe, interface.

50. What is the difference between Finalize() and Dispose()?

Answer: Dispose() is called by as an indication for an object to release any unmanaged resources it has held. Finalize() is used for the same purpose as dispose however finalize doesn't assure the garbage collection of an object. Dispose() operates determinalistically due to which it is generally preferred.

51. Explain how to add controls dynamically to the form using C#.NET.

Answer: The following code can be called on some event like page load or onload of some image or even a user action like onclick protected void add_button(Button button) { try { panel1.Controls.Add(button); // Add the control to the container on a page } catch (Exception ex) { label1.Text += ex.Message.ToString(); } }

52. What is Custom Control?

Answer: • A Custom control inherits from System.Windows.Controls.Control class. • They are compiled code (Dlls), faster to use, difficult to develop, and can be placed in toolbox. • Custom controls can be derived from different custom controls according to requirement. • Custom controls can be reused on multiple places easily. • Provide more flexibility in extending the control's behavior. • Custom controls are loosely coupled control in respect to code an UI. • Custom controls can be used just by drag and drop into the form. • Custom controls have dynamic layout.

53. Define Interface class in C#.NET.

Answer: It isan abstract class with public abstract methods with no implimentation.

54. What is difference between Class And Interface?

Answer: Class is logical representation of object. It is collection of data and related sub procedures with defination. Interface : is also a class containg methods which is not having any definations.Class does not support multiple inheritance. But interface can support.

55. Explain the purpose of tracing levels in System.Diagnostics.TraceSwitcher.

Answer: Five levels range from none to Verbose, allowing fine-tuning the tracing activities.

56. Describe delegate in detail.

Answer: A delegate is an object that can refer to a method. It means that it can hold a reference to a method. The method can be called through this reference or we can say that a delegate can invoke the method to which it refers. The same delegate can be used to call different methods during the runtime of a program by simply changing the method to which the delegate refers. The main advantage of a delegate is that it invokes the method at run time rather than compile time. Delegate in C# is similar to a function pointer in C/C++. A delegate type is declared using the keyword delegate. The prototype of a delegate declaration is given below: delegate ret-type name(parameter-list); Important Note:A delegate can call only those methods that have same signature and return type as delegate. Example: delegate string StrDemo(string str); This delegate can only call those methods that have string return type and take argument as string. Example on Delegate.using System; // Declare a delegate type. namespace Test { delegate string StrDemo(string str); class DelegateDemo { // Replaces spaces with **. public string ReplaceSpaces(string s) { Console.WriteLine("Replacing spaces with *."); return s.Replace(' ', '*'); } // Remove spaces. public string RemoveSpaces(string s) { string temp = ""; int i; Console.WriteLine("Removing spaces."); for (i = 0; i < s.Length; i++) if (s[i] != ' ') temp += s[i]; return temp; } } class MyClass { static void Main() { DelegateDemo obj = new DelegateDemo(); StrDemo strOp = new StrDemo(obj.ReplaceSpaces); string str; str = strOp("This is a test."); Console.WriteLine("Resulting string: " + str); Console.WriteLine(); strOp = new StrDemo(obj.RemoveSpaces); str = strOp("This is a test."); Console.WriteLine("Resulting string: " + str); Console.WriteLine(); Console.ReadLine(); } } } Output: Replacing spaces with *. Resulting string: This*is*a*test. Removing spaces. Resulting string: Thisisatest.

57. What is the difference between public, static and void?

Answer: public :The keyword public is an access modifier that tells the C# compiler that the Main method is accessible by anyone. static :The keyword static declares that the Main method is a global one and can be called without creating an instance of the class. The compiler stores the address of the method as the entry point and uses this information to begin execution before any objects are created. void : The keyword void is a type modifier that states that the Main method does not return any value.

58. How does C# differ from C++?

Answer: • C# doesn't support multiple inheritances while C++ does. • We can use switch statement with string values in C# while in C++ only Character and integer values supported. • Casting is Safer in C# than C++. • C# doesn't require semicolon on completion of class definition while C++ use. • In C#, Command line parameter acts differently as compared to C++.

59. What Is a "Method"?

Answer: A method is a basic part of a program. It can solve a certain problem, eventually take parameters and return a result. A method represents all data conversion a program does, to resolve a particular task. Methods consist of the program’s logic. Moreover they are the place where the “real job” is done. That is why methods can be taken as a base unit for the whole program. This on the other hand, gives us the opportunity, by using a simple block, to build bigger programs, which resolve more complex and sophisticated problems. Below is a simple example of a method that calculates rectangle’s area: static double GetRectangleArea(double width, double height) { double area = width * height; return area; }

60. Describe how a .Net application is compiled and executed.

Answer: From the source code, the compiler generates Microsoft Intermediate Language (MSIL) which is further used for the creation of an EXE or DLL. The CLR processes these at runtime. Thus, compiling is the process of generating this MSIL. The way you do it in .Net is as follows: Right-click and select Build / Ctrl-Shift-B / Build menu, Build command F5 - compile and run the application. Ctrl+F5 - compile and run the application without debugging. Compilation can be done with Debug or Release configuration. The difference between these two is that in the debug configuration, only an assembly is generated without optimization. However, in release complete optimization is performed without debug symbols.

61. When dowe declare a class as abstract in C#.NET?

Answer: When at least one of the methods in the class is abstract.

62. Define polymorphism?

Answer: Polymorphism means one name, multiple forms. It allows us to have more than one function with the same name in a program.It allows us to have overloading of operators so that an operation can exhibit different behaviours in different instances.

63. What is the use of System.Environment class in C#.NET?

Answer: The System.Environment class can be used to retrieve information like: command-line arguments the exit code environment variable settings contents of the call stack time since last system boot the version of the common language runtime

64. What are the difference between const and readonly?

Answer: A const can not be static, while readonly can be static. A const need to be declared and initialized at declaration only, while a readonly can be initialized at declaration or by the code in the constructor. A const's value is evaluated at design time, while a readonly's value is evaluated at runtime.

65. How does object pooling and connection pooling differ?

Answer: In Object pooling, you can control the number of connections. In connection pooling, you can control the maximum number reached. When using connection pooling, if there is nothing in the pool, a connection is created since the creation is on the same thread. In object pooling, the pool decides the creation of an object depending on whether the maximum is reached which in case if it is, the next available object is returned. However, this could increase the time complexity if the object is heavy.

66. What Is the Console?

Answer: The Console is a window of the operating system through which users can interact with system programs of the operating system or with other console applications. The interaction consists of text input from the standard input (usually keyboard) or text display on the standard output (usually on the computer screen). These actions are also known as input-output operations. The text written on the console brings some information and is a sequence of characters sent by one or more programs. For each console application the operating system connects input and output devices. By default these are the keyboard and the screen but they can be redirected to a file or other devices.

67. What is a Constructor?

Answer: It is the first method that are called on instantiation of a type. It provides way to set default values for data before the object is available for use. Performs other necessary functions before the object is available for use.

68. How to achieve polymorphism in C#.NET?

Answer: Polymorphism is when a class can be used as more than one type through inheritance. It can be used as its own type, any base types, or any interface type if it implements interfaces. It can be achieved in the following ways: Derived class inherits from a base class and it gains all the methods, fields, properties and events of the base class. To completely take over a class member from a base class, the base class has to declare that member as virtual.

69. What are namespaces, and how they are used?

Answer: • In .Net framework namespaces are used to manage classes. • The Key difference between .Net namespaces and java packages is that namespace doesn't define the physical layout of source file while java packages do. • Namespace define logical structure of the code. • Namespaces can be utilized via using keyword, in .net framework, many class have their namespace defined such as System.Net. • We can create our own C# source files which can relate to multiple projects.

70. Net. What are different types of configuration files in .Net framework?

Answer: The Machine.Config file, which specifies the settings that are global to a particular machine. This file is located at the following path: \WINNT\Microsoft.NET\Framework\[Framework Version]\CONFIG\machine.config The simplest way to add application-specific settings into an application configuration file is to use an application configuration file. The file is an XML file and contains add elements with key and value attributes. <?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="ApplicationTitle" value="Sample Console Application" /> <addkey="ConnectionString"value="Server=localhost;Database=Northwind;Integrated Security= false;UserId=sa;Password=;" /> </appSettings> </configuration> <authentication> The authentication section controls the type of authentication used within your Web application Windows, Forms or Passport type of authentication can be defined. Eg: <authentication mode="Windows" /> <allow> or <deny> tags can be used with authorization to allow or deny access to your web application to certain users or roles, <authorization> <allow roles="Administrators,Users" /> <deny users="*" /> </authorization>

71. What is an interface class?

Answer: An interface class is an abstract class with public abstract methods. You can inherit the class and have the methods over-ridden.

72. What is an Event?

Answer: When an action is performed, this action is noticed by the computer application based on which the output is displayed. These actions are called events. Examples of events are pressing of the keys on the keyboard, clicking of the mouse. Likewise, there are a number of events which capture your actions.

73. What are the difference between Structure and Class?

Answer: • Structures are Values types while Classes are Reference types. • In structure values stored in stack while in class value's reference stored in heap. • In structure direct values is stored while in class reference to a value is stored. • Inheritance is supported in classes while structure doesn't support. • We cannot declare destructor in structure whereas in class it is possible. • We can't have explicitly parameter less constructors in structure whereas classes can have. • Class can have protected members while structure can't have. • Structure is declared by using struct keyword while class is declared by using Class keyword. • Structures don't have memory management while classes have due to garbage collector. • New operator works in classes while not in structure.

74. What is an application domain?

Answer: • An AppDomain is a lightweight activity. • Goal of Appdomain is to isolate application from each other which is useful in hosting like Asp.net Application. • The host can destroy the Appdomain without loosing others in the process. • .Net runtime managed AppDomain memory to ensure that they don't access other's memory. • AppDomain is useful in creation and destruction of types on the fly. • AppDomain Created automatically on creation of new application by CLRHost.

75. Difference between an interface and abstract class

Answer: Some methods in the abstract class can be concrete whereas all methods in the interface are abstract.

76. What are the namespaces used in C#.NET?

Answer: Namespace is a logical grouping of class. Using System; Using System.Collections.Generic; Using System.Windows.Forms;

77. Suppose that you have two interface named IFirstInterface and ISecondInterface.In both the interface same name method SameMethod() is available .As a developer you have to implement SameMethod() separately . How will you do that give example?

Answer: using System; namespace CareerRideTest { public interface IFirstInterface { void SameMethod(); } public interface ISecondInterface { void SameMethod(); } class A : IFirstInterface, ISecondInterface { public A() { Console.WriteLine("I am in class A constructor "); } void IFirstInterface.SameMethod() { Console.WriteLine("I am in FirstInterface"); } void ISecondInterface.SameMethod() { Console.WriteLine("I am in SecondInterface"); } } class MainClass { static void Main(string[] args) { IFirstInterface objFirst = new A(); objFirst.SameMethod(); ISecondInterface objSecond = new A(); objSecond.SameMethod(); Console.ReadKey(); } } } Output:I am in class A constructor I am in FirstInterface I am in class A constructor I am in SecondInterface Note:You cannot write as A objFirst = new A (); in above program it will give error:

78. What is an abstract base class?

Answer: An abstract class is a class that is designed to be specifically used as a base class. An abstract class contains at least one pure virtual function.

79. What is Assembly manifest?

Answer: The manifest of an assembly contains assembly's data like version, scope, security information (strong name),etc. It also contains a reference to the resource and classes. It is stored in either an .exe or a .dll with Microsoft intermediate language (MSIL) code.

80. How to allow class to be inherited, but prevent the method from being over-ridden?

Answer: You can do so by declaring the class public and making the method sealed.

81. It is a bad idea to throw your own exceptions. comment

Answer: Throwing your own exceptions means there is some design problem in the program. So, instead write proper code that can handle the error.

82. How does assembly versioning work?

Answer: • There is an assembly's version called the compatibility version. • Version number is defined by four numeric parts (e.g. 5.5.3.11). • Both the name and the version of the referenced assembly are included in each reference to an assembly. • The two parts of assembly is normally seen as incompatible, but if third part is different than assemblies are deemed as 'may be compatible', and if the only fourth part of an assembly is different than assembly is compatible. • We can specify version policy in the application configuration file. • We cannot apply versioning to private assemblies; it is applied only to shared assemblies.

83. How Do Exceptions Work?

Answer: If during the normal program execution one of the methods throws an exception, the normal flow of the program is interrupted. In the example above this happens when the StreamReader is initialized. Let’s take a look on the following line: TextReader reader = new StreamReader("WrongTextFile.txt"); If this line triggers an error, the reader local variable will not be initialized and it will have its default value of null. None of the lines that follow in the method will be executed. The program will be interrupted until the CLR finds a handler that can process the exception.

84. What are the basic concepts of object oriented programming?

Answer: It is necessary to understand some of the concepts used extensively in object oriented programming. These include Objects Classes Data abstraction and encapsulation Inheritance Polymorphism Dynamic Binding Message passing.

85. Give an Arithmetical Operators ? Example?

Answer: Here are some examples of arithmetic operators and their effect: int squarePerimeter = 17; double squareSide = squarePerimeter / 4.0; double squareArea = squareSide * squareSide; Console.WriteLine(squareSide); // 4.25 Console.WriteLine(squareArea); // 18.0625 int a = 5; int b = 4; Console.WriteLine(a + b); // 9 Console.WriteLine(a + (b++)); // 9 Console.WriteLine(a + b); // 10 Console.WriteLine(a + (++b)); // 11 Console.WriteLine(a + b); // 11 Console.WriteLine(14 / a); // 2 Console.WriteLine(14 % a); // 4 int one = 1; int zero = 0; // Console.WriteLine(one / zero); // DivideByZeroException double dMinusOne = -1.0; double dZero = 0.0; Console.WriteLine(dMinusOne / zero); // -Infinity Console.WriteLine(one / dZero); // Infinity

86. What are the File System Classes?

Answer: • The file system classes are separated into two types of classes: information and utility. • Information classes derive from the FileSystemInfo base class. • Information Classes exposes all the system information about file system objects like files, directories and drives and named as FileInfo and DirectoryInfo classes. • DriveInfo class cannot derive from the FileSystemInfo class; it is an information class which represents a drive in the file system. • The utility classes have static methods to perform function on file system objects such as file system paths and Directories. • System.IO namespace contains collection of classes for files, drives and directories.

<div style="border-bottom: 1px

Show more