Toars I will smile to the world ^o^

17Nov/101

(1/3) ListView events, ItemDataBound, ItemCreated

Below are the screenshots about a user control that is using the .NET ListView control.

Display Record

The ListView control contains many different events. In these examples, the EDIT button, REMOVE button, ADD button, and SAVE button click events are handled respectively.

Of course, there are many ways of implementations to get the job done, as far as I believed, using these ItemDataBound, ItemEditing, ItemDeleting, ItemCanceling, ItemUpdating, and ItemInserting are the easiest way.

Before implementing the code, design the UI first.

<table> <thead> <tr> <th><asp:Literal ID="LitHost" runat="server" /></th> <th><asp:Literal ID="LitPointsTo" runat="server" /></th> <th><asp:Literal ID="LitTtl" runat="server" /></th> <th><asp:Literal ID="LitActions" runat="server" /></th> </tr> </thead> <tbody> <asp:ListView ID="LstItems" runat="server"> <LayoutTemplate> <tr id="itemPlaceHolder" runat="server" /> </LayoutTemplate> <ItemTemplate> <tr> <td><asp:Literal ID="LitHost" runat="server" /></td> <td><asp:Literal ID="LitPointsTo" runat="server" /></td> <td><asp:Literal ID="LitTtl" runat="server" /></td> <td> <asp:LinkButton CommandName="Edit" ID="BtnEdit" runat="server" /> <asp:LinkButton CommandName="Delete" ID="BtnRemove" runat="server" /> </td> </tr> </ItemTemplate> <EditItemTemplate> <tr> <td><asp:TextBox ID="TxtHost" runat="server" /></td> <td><asp:TextBox ID="TxtPointsTo" runat="server" /></td> <td><asp:DropDownList ID="DdlTtl" runat="server" /></td> <td> <asp:LinkButton CommandName="Update" ID="BtnSave" runat="server" /> <asp:LinkButton CommandName="Cancel" ID="BtnCancel" runat="server" /> </td> </tr> </EditItemTemplate> <InsertItemTemplate> <tr> <td><asp:TextBox ID="TxtNewHost" runat="server" /></td> <td><asp:TextBox ID="TxtNewPointsTo" runat="server" /></td> <td><asp:DropDownList ID="DdlNewTtl" runat="server" /></td> <td><asp:LinkButton ID="BtnAdd" CommandName="Insert" runat="server" /></td> </tr> </InsertItemTemplate> </asp:ListView> </tbody> </table>

In the code-behind, we need to hook up the ItemDataBound event, and bind the data source.

LstItems.ItemDataBound += new EventHandler<ListViewItemEventArgs>(LstItems_ItemDataBound); LstItems.DataSource = DnsCollection; LstItems.DataBind();

It is more flexible to handle the ItemDataBound event in the code-behind than binding the data source in the UI.

protected void LstItems_ItemDataBound(object sender, ListViewItemEventArgs e) { var item = e.Item; if (item.ItemType == ListViewItemType.DataItem) { var currentDnsRecord = (DnsRecordItem)(item as ListViewDataItem).DataItem; // When Displaying the items if (item.DataItemIndex != LstItems.EditIndex) { var litHost = item.FindControl<Literal>("LitHost"); var litPointsTo = item.FindControl<Literal>("LitPointsTo"); var litTtl = item.FindControl<Literal>("LitTtl"); litHost.Text = currentDnsRecord.HostName; litPointsTo.Text = currentDnsRecord.PointsTo; litTtl.Text = currentDnsRecord.TimeToLive; } else { // When rendering Edit item. var txtHost = item.FindControl<TextBox>("TxtHost"); var txtPointsTo = item.FindControl<TextBox>("TxtPointsTo"); var ddlTtl = item.FindControl<DropDownList>("DdlTTL"); txtHost.Text = OldDnsRecord.HostName; txtPointsTo.Text = OldDnsRecord.PointsTo; BindDdlTimeToLive(ddlTtl, OldDnsRecord.TimeToLive); } } }

If you are not quite sure the FindControl, please check my previous post, FindControl() Extention methods.

On the other hand, when you want to do something before ItemDataBound event, you can create this ItemCreated event handler.

LstItems.ItemCreated += new EventHandler<ListViewItemEventArgs>(LstItems_ItemCreated);

ItemCreated is happened when the ListView is created, and when the data items are bound to the control.
ItemCreated is raised before the ItemDataBound event.

protected void LstItems_ItemCreated(object sender, ListViewItemEventArgs e) { var item = e.Item; if (item.ItemType == ListViewItemType.DataItem) { } else if (item.ItemType == ListViewItemType.InsertItem) { } }
Filed under: .NET, C# 1 Comment
16Nov/100

(2/5) ListView events, ItemInserting, ItemDeleting

Add Record

In order to have this ADD button work, what we need is to wire the events first in the page's code behind.

LstItems.ItemInserting += new EventHandler<ListViewInsertEventArgs>(LstItems_ItemInserting);
LstItems.ItemDeleting += new EventHandler<ListViewInsertEventArgs>(LstItems_ItemDeleting);
LstItems.InsertItemPosition = InsertItemPosition.LastItem;

And usually, we will have this insert template either in the first item of this ListView or the last item. In this example, it is in the last item.

Button "Add" click.

protected void LstItems_ItemInserting(object sender, ListViewInsertEventArgs e)
{
    if (!Page.IsValid)
    return;

    var txtNewHost = e.Item.FindControl<TextBox>("TxtNewHost");
    var txtNewPointsTo = e.Item.FindControl<TextBox>("TxtNewPointsTo");
    var ddlNewTtl = e.Item.FindControl<DropDownList>("DdlNewTTL");

    var host = txtNewHost.Text;
    var pointsTo = txtNewPointsTo.Text;
    var ttl = ddlNewTtl.SelectedValue;

    var result = AddNewRecord();
    if (result == Status.Ok)
    {
        // Rebind the ListView
    }
    else
    {
        // Do error handling
    }
}

Button "Remove" click.

protected void LstItems_ItemDeleting(object sender, ListViewInsertEventArgs e)
{
    var item = LstItems.Items[e.ItemIndex];

    var result = RemoveRecord();
    if (result == Status.Ok)
    {
        LstItems.EditIndex = -1;

        // Rebind the ListView
    }
    else
    {
        // Do error handling
    }
}
Filed under: .NET, C# No Comments
15Nov/100

(3/3) ListView events, ItemEditing, ItemCanceling, ItemUpdating


Edit Record

Same for this Edit Record, Save Record and Cancel button click events.

Wire the events in the code-behind first.

LstItems.ItemEditing += new EventHandler<ListViewItemEventArgs>(LstItems_ItemEditing); LstItems.ItemUpdating += new EventHandler<ListViewItemEventArgs>(LstItems_ItemUpdating); LstItems.ItemCanceling += new EventHandler<ListViewItemEventArgs>(LstItems_ItemCanceling);

Button "Edit" click.

protected void LstItems_ItemEditing(object sender, ListViewItemEventArgs e) { var item = LstItems.Items[e.NewEditIndex]; // Save the currently selected item to OldDnsRecord
// ReBind the ListView }

Button "Save" click.

protected void LstItems_ItemUpdating(object sender, ListViewItemEventArgs e) { if (!Page.IsValid) return; var txtNewHost = e.Item.FindControl<TextBox>("TxtNewHost"); var txtNewPointsTo = e.Item.FindControl<TextBox>("TxtNewPointsTo"); var ddlNewTtl = e.Item.FindControl<DropDownList>("DdlNewTTL"); var host = txtNewHost.Text; var pointsTo = txtNewPointsTo.Text; var ttl = ddlNewTtl.SelectedValue; var result = UpdateExistingRecord(); if (result == Status.Ok) { LstItems.EditIndex = -1; // Rebind the ListView } else { // Do error handling } }

Button "Cancel" click.

protected void LstItems_ItemCanceling(object sender, ListViewItemEventArgs e) { LstItems.EditIndex = -1; // Rebind the ListView }
Filed under: .NET, C# No Comments
14Nov/100

ASP.NET Events

  • HttpApplication.BeginRequest
  • HttpApplication.AuthenticateRequest
  • HttpApplication.PostAuthenticateRequest
  • HttpApplication.AuthorizeRequest
  • HttpApplication.PostAuthorizeRequest
  • HttpApplication.ResolveRequestCache
  • HttpApplication.PostResolveRequestCache
  • HttpApplication.MapRequestHandler
  • HttpApplication.PostMapRequestHandler
  • HttpApplication.AcquireRequestState
  • HttpApplication.PostAcquireRequestState
  • HttpApplication.PreRequestHandlerExecute
  • Page.FrameworkInitialize
  • Page.InitializeCulture
  • Page.OnPreInit
  • MasterPage.FrameworkInitialize
  • MasterPageControl.FrameworkInitialize
  • PageControl.FrameworkInitialize
  • MasterPageControl.OnInit
  • PageControl.OnInit
  • MasterPage.OnInit
  • Page.OnInit
  • Page.OnInitComplete
  • Page.LoadPageStateFromPersistenceMedium
    If IsPostBack
  • Page.LoadControlState
    If IsPostBack
  • MasterPageControl.LoadControlState
    If IsPostBack, RegisterRequiresControlState was called and control state contains elements
  • PageControl.LoadControlState
    If IsPostBack, RegisterRequiresControlState was called and control state contains elements
  • MasterPageControl.LoadViewState
    If IsPostBack and ViewState contains elements
  • PageControl.LoadViewState
    If IsPostBack and ViewState contains elements
  • Page.OnPreLoad
  • Page.OnLoad
  • MasterPage.OnLoad
  • MasterPageControl.OnLoad
  • PageControl.OnLoad
  • {PageControl|MasterPageControl}.OnCustomEvent
    If a custom event was fired on a control declared on the page/master page
  • {PageControl|MasterPageControl}.OnBubbleEvent
    If a custom event was fired on a control declared on the page/master page
  • {Page|MasterPage}.OnBubbleEvent
    If a custom event was fired on a control declared on the page/master page
  • Page.OnBubbleEvent
    If a custom event was fired
  • Page.OnLoadComplete
  • ClientCallbackControl.RaiseCallbackEvent
    If in a client callback asynchronous request
  • ClientCallbackControl.GetCallbackResult
    If in a client callback asynchronous request
  • Page.OnPreRender
    If not in an asynchronous postback
  • MasterPage.OnPreRender
    If not in an asynchronous postback
  • MasterPageControl.OnPreRender
    If Visible
  • PageControl.OnPreRender
    If Visible and not in an asynchronous postback
  • Page.OnPreRenderComplete
    If not in an asynchronous postback
  • Page.SaveControlState
    If not in an asynchronous postback and RegisterRequiresControlState is called for the page and control state contains additiona values
  • MasterPageControl.SaveControlState
    If not in an asynchronous postback and RegisterRequiresControlState is called for the master page control and control state contains additiona values
  • PageControl.SaveControlState
    If not in an asynchronous postback and RegisterRequiresControlState is called for the page control and control state contains additiona values
  • Page.SaveViewState
    If not in an asynchronous postback
  • MasterPage.SaveViewState
    If not in an asynchronous postback
  • MasterPageControl.SaveViewState
    If not in an asynchronous postback
  • PageControl.SaveViewState
    If not in an asynchronous postback
  • Page.SavePageStateToPersistenceMedium
    If not in an asynchronous postback
  • Page.OnSaveStateComplete
    If not in an asynchronous postback
  • Page.Render
    If not in an asynchronous postback
  • MasterPage.Render
    If not in an asynchronous postback
  • MasterPageControl.Render
    If Visible and not in an asynchronous postback
  • PageControl.Render
    If Visible and not in an asynchronous postback
  • Page.OnCommitTransaction
    If Transaction = Required or RequiresNew and a transaction was committed or no transaction was created
  • Page.OnAbortTransaction
    If Transaction = Required or RequiresNew and a transaction was rolled back
  • MasterPageControl.OnUnload
  • MasterPageControl.Dispose
  • PageControl.OnUnload
  • PageControl.Dispose
  • MasterPage.OnUnload
  • MasterPage.Dispose
  • Page.OnUnload
  • Page.Dispose
  • HttpApplication.PostRequestHandlerExecute
  • HttpApplication.ReleaseRequestState
  • HttpApplication.PostReleaseRequestState
  • HttpApplication.UpdateRequestCache
  • HttpApplication.PostUpdateRequestCache
  • HttpApplication.LogRequest
  • HttpApplication.PostLogRequest
  • HttpApplication.EndRequest
  • HttpApplication.PreSendRequestHeaders
  • HttpApplication.PreSendRequestContent
Filed under: .NET, C# No Comments
14Nov/100

ASP.NET Page life cycle

  1. Page.OnPreInit
  2. MasterPageControl.OnInit (for each control on the master page)
  3. Control.OnInit (for each contol on the page)
  4. MasterPage.OnInit
  5. Page.OnInit
  6. Page.OnInitComplete
  7. Page.LoadPageStateFromPersistenceMedium
  8. Page.LoadViewState
  9. MasterPage.LoadViewState
  10. Page.OnPreLoad
  11. Page.OnLoad
  12. MasterPage.OnLoad
  13. MasterPageControl.OnLoad (for each control on the master page)
  14. Control.OnLoad (for each control on the page)
  15. OnXXX (control event)
  16. MasterPage.OnBubbleEvent
  17. Page.OnBubbleEvent
  18. Page.OnLoadComplete
  19. Page.OnPreRender
  20. MasterPage.OnPreRender
  21. MasterPageControl.OnPreRender (for each control on the master page)
  22. Control.OnPreRender (for each control on the page)
  23. Page.OnPreRenderComplete
  24. MasterPageControl.SaveControlState (for each control on the master page)
  25. Control.SaveControlState (for each control on the page)
  26. Page.SaveViewState
  27. MasterPage.SaveViewState
  28. Page.SavePageStateToPersistenceMedium
  29. Page.OnSaveStateComplete
  30. MasterPageControl.OnUnload (for each control on the master page)
  31. Control.OnUnload (for each control on the page)
  32. MasterPage.OnUnload
  33. Page.OnUnload
Filed under: .NET, C# No Comments
11Nov/100

C# Questions and Answers – 09

  • How big is the datatype int in .NET?
    32 bits.
  • How big is the char?
    16 bits (Unicode).
  • How do you initiate a string without escaping each backslash?
    Put an @ sign in front of the double-quoted string.
  • What are valid signatures for the Main function?
    • public static void Main()
    • public static int Main()
    • public static void Main( string[] args )
    • public static int Main(string[] args )
  • Does Main() always have to be public?
    No.
  • How do you initialize a two-dimensional array that you don’t know the dimensions of?
    • int [, ] myArray; //declaration
    • myArray= new int [5, 8]; //actual initialization
  • What’s the access level of the visibility type internal?
    Current assembly.
  • What’s the difference between struct and class in C#?
    • Structs cannot be inherited.
    • Structs are passed by value, not by reference.
    • Struct is stored on the stack, not the heap.
  • Explain encapsulation
    The implementation is hidden, the interface is exposed.
  • What data type should you use if you want an 8-bit value that’s signed?
    sbyte.
  • Speaking of Boolean data types, what’s different between C# and C/C++?
    There’s no conversion between 0 and false, as well as any other number and true, like in C/C++.
  • Where are the value-type variables allocated in the computer RAM?
    Stack.
  • Where do the reference-type variables go in the RAM?
    The references go on the stack, while the objects themselves go on the heap. However, in reality things are more elaborate.
  • What is the difference between the value-type variables and reference-type variables in terms of garbage collection?
    The value-type variables are not garbage-collected, they just fall off the stack when they fall out of scope, the reference-type objects are picked up by GC when their references go null.
  • How do you convert a string into an integer in .NET?
    Int32.Parse(string), Convert.ToInt32()
  • How do you box a primitive data type variable?
    Initialize an object with its value, pass an object, cast it to an object
  • Why do you need to box a primitive variable?
    To pass it by reference or apply a method that an object supports, but primitive doesn’t.
  • What’s the difference between Java and .NET garbage collectors?
    Sun left the implementation of a specific garbage collector up to the JRE developer, so their performance varies widely, depending on whose JRE you’re using. Microsoft standardized on their garbage collection.
  • How do you enforce garbage collection in .NET?
    System.GC.Collect();
  • 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.
  • What’s different about namespace declaration when comparing that to package declaration in Java?
    No semicolon. Package declarations also have to be the first thing within the file, can’t be nested, and affect all classes within the file.
  • What’s the difference between const and readonly?
    You can initialize readonly variables to some runtime values. Let’s say your program uses current date and time as one of the values that won’t change. This way you declare

    public readonly string DateT = new DateTime().ToString().

  • Can you create enumerated data types in C#?
    Yes.
  • What’s different about switch statements in C# as compared to C++?
    No fall-throughs allowed.
  • What happens when you encounter a continue statement inside the for loop?
    The code for the rest of the loop is ignored, the control is transferred back to the beginning of the loop.
  • 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.
  • Describe the compilation process for .NET code?
    Source code is compiled and run in the .NET Framework using a two-stage process. First, source code is compiled to Microsoft intermediate language (MSIL) code using a .NET Framework-compatible compiler, such as that for Visual Basic .NET or Visual C#. Second, MSIL code is compiled to native code.
  • Name any 2 of the 4 .NET authentification methods
    ASP.NET, in conjunction with Microsoft Internet Information Services (IIS), can authenticate user credentials such as names and passwords using any of the following authentication methods:

    • Windows: Basic, digest, or Integrated Windows Authentication (NTLM or Kerberos).
    • Microsoft Passport authentication
    • Forms authentication
    • Client Certificate authentication
  • How do you turn off SessionState in the web.config file?
    In the system.web section of web.config, you should locate the httpmodule tag and you simply disable session by doing a remove tag with attribute name set to session.

    <httpModules>
    <remove name=”Session” />
    </httpModules>

  • What is main difference between Global.asax and Web.Config?
    ASP.NET uses the global.asax to establish any global objects that your Web application uses. The .asax extension denotes an application file rather than .aspx for a page file. Each ASP.NET application can contain at most one global.asax file. The file is compiled on the first page hit to your Web application. ASP.NET is also configured so that any attempts to browse to the global.asax page directly are rejected. However, you can specify application-wide settings in the web.config file. The web.config is an XML-formatted text file that resides in the Web site’s root directory. Through Web.config you can specify settings like custom 404 error pages, authentication and authorization settings for the Web site, compilation options for the ASP.NET Web pages, if tracing should be enabled, etc.
Filed under: .NET, C#, Interviews No Comments
11Nov/100

C# Questions and Answers – 08

  • What’s the implicit name of the parameter that gets passed into the class’ set method?
    Value, and it’s datatype depends on whatever variable we’re changing.
  • How do you inherit from a class in C#?
    Place a colon and then the name of the base class.
  • Does C# support multiple inheritance?
    No, use interfaces instead.
  • When you inherit a protected class-level variable, who is it available to?
    Classes in the same namespace.
  • Are private class-level variables inherited?
    Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited. But they are.
  • Describe the accessibility modifier protected internal.
    It’s available to derived classes and classes within the same Assembly (and naturally from the base class it’s declared in).
  • C# provides a default constructor for me. I write a constructor that takes a string as a parameter, but want to keep the no parameter one. How many constructors should I write?
    Two. Once you write at least one constructor, C# cancels the freebie constructor, and now you have to write one yourself, even if there’s no implementation in it.
  • What’s the top .NET class that everything is derived from?
    System.Object.
  • How’s method overriding different from overloading?
    When overriding, you change the method behavior for a derived class. Overloading simply involves having a method with the same name within the class.
  • What does the keyword virtual mean in the method definition?
    The method can be over-ridden.
  • Can you declare the override method static while the original method is non-static?
    No, you can’t, the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override.
  • Can you override private virtual methods?
    No, moreover, you cannot access private methods in inherited classes, have to be protected in the base class to allow any sort of access.
  • Can you prevent your class from being inherited and becoming a base class for some other classes?
    Yes, that’s what keyword sealed in the class definition is for. The developer trying to derive from your class will get a message: cannot inherit from Sealed class WhateverBaseClassName. It’s the same concept as final class in Java.
  • Can you allow class to be inherited, but prevent the method from being over-ridden?
    Yes, just leave the class public and make the method sealed.
  • What’s an abstract class?
    A class that cannot be instantiated. A concept in C++ known as pure virtual method. A class that must be inherited and have the methods over-ridden. Essentially, it’s a blueprint for a class without any implementation.
  • When do you absolutely have to declare a class as abstract (as opposed to free-willed educated choice or decision based on UML diagram)?
    When at least one of the methods in the class is abstract. When the class itself is inherited from an abstract class, but not all base abstract methods have been over-ridden.
  • What’s an interface class? It’s an abstract class with public abstract methods all of which must be implemented in the inherited classes.
  • Why can’t you specify the accessibility modifier for methods inside the interface?
    They all must be public. Therefore, to prevent you from getting the false impression that you have any freedom of choice, you are not allowed to specify any accessibility, it’s public by default.
  • Can you inherit multiple interfaces?
    Yes, why not.
  • And if they have conflicting method names?
    It’s up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data, but as far as compiler cares you’re okay.
  • What’s the difference between an interface and abstract class?
    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 is ok in abstract classes.
  • How can you overload a method?
    Different parameter data types, different number of parameters, different order of parameters.
  • If a base class has a bunch of overloaded constructors, and an inherited class has another bunch of overloaded constructors, can you enforce a call from an inherited constructor to an arbitrary base constructor?
    Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class.
  • What’s the difference between System.String and System.StringBuilder classes?
    System.String is immutable, System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.
  • Is it namespace class or class namespace?
    The .NET class library is organized into namespaces. Each namespace contains a functionally related group of classes so natural namespace comes first.
Filed under: .NET, C#, Interviews No Comments
11Nov/100

C# Questions and Answers – 07

  • Are private class-level variables inherited?
    Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited. But they are.
  • Why does DllImport not work for me?
    All methods marked with the DllImport attribute must be marked as public static extern.
  • Why does my Windows application pop up a console window every time I run it?
    Make sure that the target type set in the project properties setting is set to Windows Application, and not Console Application. If you’re using the command line, compile with /target:winexe, not /target:exe.
  • Why do I get an error (CS1006) when trying to declare a method without specifying a return type?
    If you leave off the return type on a method declaration, the compiler thinks you are trying to declare a constructor. So if you are trying to declare a method that returns nothing, use void. The following is an example: // This results in a CS1006 error public static staticMethod (mainStatic obj) // This will work as wanted public static void staticMethod (mainStatic obj)
  • Why do I get a syntax error when trying to declare a variable called checked?
    The word checked is a keyword in C#.
  • Why do I get a security exception when I try to run my C# app?
    Some security exceptions are thrown if you are working on a network share. There are some parts of the frameworks that will not run if being run off a share (roaming profile, mapped drives, etc.). To see if this is what’s happening, just move the executable over to your local drive and see if it runs without the exceptions. One of the common exceptions thrown under these conditions is System.Security.SecurityException. To get around this, you can change your security policy for the intranet zone, code group 1.2, (the zone that running off shared folders falls into) by using the caspol.exe tool.
  • Why do I get a CS5001: does not have an entry point defined error when compiling?
    The most common problem is that you used a lowercase ‘m’ when defining the Main method. The correct way to implement the entry point is as follows: class test { static void Main(string[] args) {} }
  • What optimizations 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.
  • What is the syntax for calling an overloaded constructor within a constructor (this() and constructorname() does not compile)?
    The syntax for calling another constructor is as follows:

    class B
    {
    	B(int i)
    	{
    	}
    } 
    
    class C : B
    {
    	C() : base(5) // call base constructor B(5)
    	{
    	} 
    
    	C(int i) : this() // call C()
    	{
    	} 
    
    	public static void Main()
    	{
    	}
    }
  • What is the equivalent to regsvr32 and regsvr32 /u a file in .NET development?
    Try using RegAsm.exe. Search MSDN on Assembly Registration Tool.
  • What is the difference between a struct and a class in C#?
    From language spec: The list of similarities between classes and structs is as follows. Longstructs can implement interfaces and can have the same kinds of members as classes. Structs differ from classes in several important ways; however, structs are value types rather than reference types, and inheritance is not supported for structs. Struct values are stored on the stack or in-line. Careful programmers can sometimes enhance performance through judicious use of structs. For example, the use of a struct rather than a class for a Point can make a large difference in the number of memory allocations performed at runtime. The program below creates and initializes an array of 100 points. With Point implemented as a class, 101 separate objects are instantiated-one for the array and one each for the 100 elements.
  • My switch statement works differently than in C++! Why?
    C# does not support an explicit fall through for case blocks. The following code is not legal and will not compile in C#:

    switch(x)
    {
    	case 0: // do something
    	case 1: // do something as continuation of case 0
    	default: // do something in common with
    		//0, 1 and everything else
    	break;
    }

    To achieve the same effect in C#, the code must be modified as shown below (notice how the control flows are explicit):

    class Test
    {
    	public static void Main() {
    		int x = 3;
    		switch(x)
    		{
    			case 0: // do something
    			goto case 1;
    			case 1: // do something in common with 0
    			goto default;
    			default: // do something in common with 0, 1, and anything else
    			break;
    		}
    	}
    }
  • Is there regular expression (regex) support available to C# developers?
    Yes. The .NET class libraries provide support for regular expressions. Look at the System.Text.RegularExpressions namespace.
  • Is there any sample C# code for simple threading?
    Yes:

    using System;
    using System.Threading;
    class ThreadTest
    {
    	public void runme()
    	{
    		Console.WriteLine("Runme Called");
    	}
    	public static void Main(String[] args)
    	{
    		ThreadTest b = new ThreadTest();
    		Thread t = new Thread(new ThreadStart(b.runme));
    		t.Start();
    	}
    }
  • Is there an equivalent of exit() for quitting 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.
  • Is there a way to force garbage collection?
    Yes. Set all references to null and then call System.GC.Collect(). If you need to have some objects destructed, and System.GC.Collect() doesn’t seem to be doing it for you, you can force finalizers to be run by setting all the references to the object to null and then calling System.GC.RunFinalizers().
  • Is there a way of specifying which block or loop to break out of when working with nested loops?
    The easiest way is to use goto:

    using System;
    class BreakExample
    {
    	public static void Main(String[] args) {
    		for(int i=0; i<3; i++)
    		{
    			Console.WriteLine("Pass {0}: ", i);
    			for( int j=0 ; j<100 ; j++ )
    			{
    				if ( j == 10)
    					goto done;
    				Console.WriteLine("{0} ", j);
    			}
    			Console.WriteLine("This will not print");
    		}
    		done:
    			Console.WriteLine("Loops complete.");
    	}
    }
  • 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.
Filed under: .NET, C#, Interviews No Comments