C# Interview Questions 5

By | May 13, 2014

What are indexers? What are their advantages over arrays?An indexer enables you to treat an object like an array.It helps you to acces the arrays in a class using the class name. Indexer enables you to use bracket notation ([]) with an object to set and get a value from an object.They encapsulate method calls into more convenient representation of value access and value setting. public dataType this[int index] {   get   {      //Code to get some value from a array      if (index < 0)                 return “negative”;             else if (index > max)                 return “Infinity”;             else                 return arr[index];       }   set   {      arr[index]=value;   } }    Indexers makes your code more readable and easier to understand.You can create mulltiple indexers for a class.  Signature of each indexer should be unique.  The signature of an indexer is considered as the number and types of its formal parameters return data type of the indexer is not part of signature.They help you to represent as array values which may have no similarities to arrays as internal representation.You are not limited to using integers as indexes. You can use strings to achieve the result used in the Hash class and many others. Use indexer only when the representation of the class data as multiple objects is proper.

How would you implement singleton pattern in C#? Singleton Pattern Definition The Singleton pattern ensures that a class only has one instance and provides a global point of access to it from a well-known access point. The class implemented using this pattern is responsible for keeping track of its sole instance rather than relying on global variables to single instances of objects Often, this pattern is used to represent parts of the system that there can only be one of, like the file system or window manager. Or, parts of your application that there will only ever be one of. C# Implementation 1. The constructor should be private. 2. Provide a static method, which returns an instance of the class. 3. Use a static variable to check whether already one instance is created or not. if already an instance is there , returns a null using System; class  SingleInstanceClass<o:p></o:p> {          private static SingleInstanceClass sic= null;    private static bool instanceFlag = false;  private SingleInstanceClass()           {              }          public static SingleInstanceClass Create()          {                if(! instanceFlag)                  {              sic = new SingleInstanceClass();                 instanceFlag = true;               return sic;               }          else              {              return null;              }              }      protected void Finalize()          {             instanceFlag = false;       } } class MyClient {              public static void Main()                  {             SingleInstanceClass sic1,sic2;                sic1 = SingleInstanceClass.Create();             if(sic1 != null)                  Console.WriteLine(“OK”);          sic2 = SingleInstanceClass.Create();             if(sic2 == null)             Console.WriteLine(“NO MORE OBJECTS”);         } } The above program returns a null value when try to create an object second time. But instead of returning null, it is possible to return already existing object ‘sic’ by changing ‘return null’ to ‘return sic’ in the above program.<o:p></o:p>

What is native image cache? The native image cache is a reserved area of the global assembly cache. Once you create a native image for an assembly, the runtime automatically uses that native image each time it runs the assembly. You do not have to perform any additional procedures to cause the runtime to use a native image. Running Ngen.exe on an assembly allows the assembly to load and execute faster, because it restores code and data structures from the native image cache rather than generating them dynamically.   Important: A native image is a file containing compiled processor-specific machine code. Note that the native image that Ngen.exe generates cannot be shared across Application Domains. Therefore, you cannot use Ngen.exe in application scenarios, such as ASP.NET, that require assemblies to be shared across application domains.   Note   To run Ngen.exe, you must have administrative privileges

What is called sealed classes?Can we derive sealed classes? Sealed classes are those classes which cannot be inherited / derived by any other classes. These Classes are used to restrict the user boundaries. In VB.Net you can create these classes using “NonInheritable” keyword.

How would you register javascript in ASP.NET through code behind? The common way to accomplish this is to use RegisterStartupScript and the RegisterClientScriptBlock methods of the Page class.   Page.RegisterStartupScript – This method adds JavaScript to the web form right before the ending </FORM>tag. This wouls be best used when we want to initiate a javascript function when the page is loaded. It takes two parameters — the first being the key of the script and the —  the second being the script itself (represented as a string).   private void Page_Load(object sender, System.EventArgs e) {            —–            —–            Page.RegisterStartupScript(“UserScript”,                        ” language=javascript>” +                         “function HelloWorld() { alert(‘Hello World’); }</SCRIPT> “);           Button1.Attributes[“onclick”] = “HelloWorld()”;           —–           —– }   Page.RegisterClientScriptBlock – This method adds JavaScript to the web form, right after the <FORM runat=”server”>declaration.  It also takes two parameters— the first being the key of the script and the second being the script itself (represented as a string).   The main difference between the two methods is that the RegisterStartupScript method places the JavaScript at the bottom of the ASP.NET page right before the closing </FORM> element while RegisterClientScriptBlock method places the JavaScript directly after the opening <FORM>element in the page.

Can we use win32api dlls in .net? Explain how? If you talk about win32dll they are written in unmanged code. PInvoke helps us to call unmanged code from manage code. It locate and invoke the code and marshal their arguments at run time. In C# we use DLLImport as attribute to call win32api dll.

What is the difference between setting an object to null and calling dispose method of the object ? E.g. Object obj = new Object(); obj = null obj.dispose() When we set any object to null, that means that object is subject to garbage collection. But we dont have any control when exactly garbage collector reclaim memory and resources from this object. So in case we have occupied some heavy resources in any object, its better to implement a Dispose() method. So on calling the dispose() method explicitly, we can free the resources.

What is the difference between Constant and Readonly? ‘const’: Can’t be static. Value is evaluated at compile time. Initiailized at declaration only. ‘readonly’: Can be either instance-level or static. Value is evaluated at run time. Can be initialized in declaration or by code in the constructor.

What benefit does your code receive if you decorate it with attributes demanding specific Security permissions? Following are the benefits of using attribute based declarative security , essentially all the relevant information is stored in the asssembly metadata on compilation and based on permissions of the calling code , CLR will make sure that application or assembly doesn’t even get loaded in case doesn’t have relevant permissions vis a vis Imperative security , where everything is checked in assembly code and assembly will invariably get loaded and executed before it checks for any such issue or lack of permissions .   So , benefits of Declarative security are :   1. Inducing efficiency as all relevant information is stored in the metadata . 2. Cleaner code as security is not mixed with program logic it’s done cleanly using attributes .

How do you define pointers in c#? Pointers in C# are syntactically used in the same way as you would use in c/c++. The only thing that is important to note is that, all code that is going to use pointers or address of operators is unsafe in .NET world and thus has to be marked with an unsafe modifier or has to be enclosed in an “unsafe” block. E.g. unsafe modifer:- unsafe void someFuncA(int *x) { //…do something }   unsafe static void Main() { int j = 100; someFunc(&j); } unsafe block:-   void someFunction() { int j = 10; unsafe { int* i = &j; } }   Lastly, all source code which contains “unsafe” code has to be compiled with “/unsafe” compiler option.  

What is shallow copying ? How does MemberWiseClone method work ? A shallow copy creates a new instance of the same type as the original object, and then copies the nonstatic fields of the original object. If the field is a value type, a bit-by-bit copy of the field is performed. If the field is a reference type, the reference is copied but the referred object is not; therefore, the reference in the original object and the reference in the clone point to the same object. In contrast, a deep copy of an object duplicates everything directly or indirectly referenced by the fields in the object. MemberwiseClone method, creates a new instance of the source object and then does a bit-by-bit copy of value types and for reference types only the reference is copied. As a result both the original object and the clone end-up pointing to the same objects that the original object refers. And this is exactly what a copy constructor in C++ does :)!   So, e.g. If X is the object in context and it reference objects Y and Z then a shallow copy A of X will refer to Y and Z!

What is the difference between a Debug and Release build? Is there a significant speed difference? The biggest difference between these is that: In a debug build the complete symbolic debug information is emitted to help while debugging applications and also the code optimization is not taken into account. While in release build the symbolic debug info is not emitted and the code execution is optimized. Also, because the symbolic info is not emitted in a release build, the size of the final executable is lesser than a debug executable.   One can expect to see funny errors in release builds due to compiler optimizations or differences in memory layout or initialization. These are ususally referred to as Release – Only bugs 🙂   In terms of execution speed, a release executable will execute faster for sure, but not always will this different be significant.

Leave a Reply