Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Wednesday, September 26, 2007

C# Tips

I am working in C# 2005

1.Modal Dialog and Modeless Dialog in C#
2.C# MDI forms
3.Opening the Chm file
4.CheckOnClick property in a menuitem
 set the Checked property as true or false

Modal Dialog and Modeless Dialog in C# :
-------------------------------------------------------------
if we are having Two Forms in our Project,  From the  Form1, we will display the Form2 as Modal and Modeless dialog.

Class Form2
{

}

class  Form1
{
     void btnShowForm2_Click()
     {
 Form2 frm = new Form2();

 frm.Show() ;// For Modeless Dialog
 frm.ShowDialog() ;//  This is for Modal dialog
 
     }
}

2.C# MDI forms
----------------------
     From Main Form, we will create the another Form means
this can be made as MDI forms.

 Wecan display more than one forms at a time in MDI forms.

For the parent Form, we have to enable the IsMdiContainer property as true.

and then drill down in to the coding as follows :

 class ChildForm
 {
 }
 class ParentForm
 {
  
  //this.IsMdiContainer = true;

  private void mnuShowChildForm_Click()
  {
   ChildForm frm = new ChildForm();
   frm.MdiParent = this;
   frm.Show();
  }
 }


Only MdiParent property of the child form is set to the Parent form's Object.

 
3. Sometimes we faced the problem in opening chm files content display problem.

while opening the chm file, sometimes it displays the dialog with "always ask before opening this file"  check box.

if this check box is not selected by us then it will not display the chm contents. So To display the chm file contents, we must enable

"always ask before opening this file"  check box.

4.CheckOnClick property in a menu item  Sometimes we may need Checked property in a menuitem. For Instance, if the user selects the menuitem then it will show the Checked mark in a menuitem and if we select once again, the checkbox will
not be shown. this selection process takes place continously like Toggle on or off.

 
 For Doing this one, the menu item is having the property CheckOnClick .

if we enable this property, then we can display the check mark and we can change the execution behavior also based on the check mark.

 CheckedState property is set to true or false based on whether the check  mark is currently displayed in a menuitem or not.

This feature can be aptly used in the following Scenario.

 if we have MDI parent form, based on the checked selection of the menuitem we have to display the MDI child form.


if the menuitem is selected for the first time, we have to display the child form. if the menuitem is selected once again, then the child form must be

hided...

 By default set the menuitem's CheckOnClick property as true and Checked property as false.

  For doing this one , add the menu event handler as follows :

 void mnuShowChildForm_Click()
 {
  if( mnuShowChildForm.Checked == true)
  {
   childFormObject.Show();
  }
  else
  {
   childFormObject.Hide();
  }
 }
 

 

 

Tuesday, September 25, 2007

?? operator (C#)

The ?? operator returns the left-hand operand if it is not null, or else it returns the right operand. For example:

    int? x = null;

    ...

    // y = x, unless x is null, in which case y = -1.

    int y = x ?? -1;

The ?? operator also works with reference types:

    //message = param, unless param is null

    //in which case message = "No message"

    string message = param ?? "No message" ;

Tuesday, September 11, 2007

Interoperability Tips

Interoperability :

 [DllImport("MAPI32.DLL", CharSet = CharSet.Ansi)]
        public static extern UInt32 MAPISendMail(IntPtr lhSession, IntPtr ulUIParam,
         MapiMessage lpMessage, UInt32 flFlags, UInt32 ulReserved);

 

if we want to rename the MAPISendMail fn  as SendMail within C# , How can we do it ?

we can do the following.

 

    [DllImport("MAPI32.DLL", EntryPoint = "MAPISendMail", CharSet = CharSet.Ansi)]
        public static extern UInt32 SendMail(IntPtr lhSession, IntPtr ulUIParam,
         MapiMessage lpMessage, UInt32 flFlags, UInt32 ulReserved);

 

 EntryPoint = "MAPISendMail"  // specified function address is obtained from the DLL


So In our C# application we can simply call

 SendMail( ...)
 
 
Literally what will happen is the address of the MAPISendMail() fn is assigned to the SendMail() fn.
 
So if we call the SendMail() fn from C#, it will in turn calls the MAPISendMail() functionality from MAPI32.dll
 
 

Wednesday, August 8, 2007

Adventures in .NET 3.5

Tuesday, August 7, 2007

C# 2.0 Features

C# 2.0 new features (.NET framework SDK):
1.Partial classes allow class implementation across more than one file. This permits breaking down very large classes, or is useful if some parts of a class are automatically generated.
2.Generics or parameterized types. This is a .NET 2.0 feature supported by C#. Unlike C++ templates, .NET parameterized types are instantiated at runtime rather than by the compiler; hence they can be cross-language whereas C++ templates cannot. They support some features not supported directly by C++ templates such as type constraints on generic parameters by use of interfaces. On the other hand, C# does not support non-type generic parameters. Unlike generics in Java, .NET generics use reification to make parameterized types first-class objects in the CLI Virtual Machine, which allows for optimizations and preservation of the type information.
3.Static classes that cannot be instantiated, and that only allow static members. This is similar to the concept of module in many procedural languages.
4.A new form of iterator that provides generator functionality, using a yield return construct similar to yield in Python.
// Method that takes an iterable input (possibly an array) and returns all even numbers.
public static IEnumerable GetEven(IEnumerable numbers)
{
foreach (int i in numbers)
{
if (i % 2 == 0) yield return i;
}
}

5.Anonymous delegates providing closure functionality.

public void Foo(object parameter)
{
// ...

ThreadPool.QueueUserWorkItem(delegate
{
// anonymous delegates have full access to local variables of the enclosing method
if (parameter == ...)
{
// ...
}

// ...
});
}

6.Covariance and contravariance for signatures of delegates
7. The accessibility of property accessors can be set independently. Example:

string status = string.Empty;
public string Status
{
get { return status; } // anyone can get value of this property,
protected set { status = value; } // but only derived classes can change it
}

8.Nullable value types (denoted by a question mark, e.g. int? i = null;) which add null to the set of allowed values for any value type. This provides improved interaction with SQL databases, which can have nullable columns of types corresponding to C# primitive types: an SQL INTEGER NULL column type directly translates to the C# int?.
int? i = null;
object o = i;
if (o == null) Console.WriteLine("Correct behaviour - you have a runtime version from September 2005 or later");
else Console.WriteLine("Incorrect behaviour - you are running a pre-release runtime (from before September)");
When copied into objects, the official release boxes values from Nullable instances, so null values and null references are considered equal.
9. Coalesce operator: (??) returns the first of its operands which is not null
object nullObj = null;
object obj = new Object();
return nullObj ?? obj; // returns obj

The primary use of this operator is to assign a nullable type to a non-nullable type with an easy syntax:

int? i = null;
int j = i ?? 0; // Unless i is null, initialize j to i. Else (if i is null), initialize j to 0.

Sunday, August 5, 2007

A Developers Toolkit for C# and .Net

A developer, no matter how skilled, is dependent on the tools at his disposal. There are numerous free tools to aid in .Net development; from source control to debugging to documentation and profiling. Here, I've compiled a complete list of tools that I've used for years that cover the entire development lifecycle.

C# and .Net are a powerful language and platform for developing software. The high levels of abstraction, garbage collection, architecture, and runtime provide an amazing platform for writing high quality software. It's a great start, but it's not enough.

In the end, quality software comes down to developer skill and organization. This article will provide some links to free tools that every .Net developer should have on hand in order to write high quality software. If you don't know what a tool does, I encourage you to explore it, you may learn something new about source control, test driven development, profiling, continual integration, or debugging that you didn't know before.

What follows is a best of breed toolkit that I use personally and professionally almost every day. All the tools are freely available for download online (with the exception of the full Visual Studio 2005 suite).

IDE
Visual Studio 2005(Not Free) - In my opinion it's the best IDE in the world. Supports many languages, integrated web server, code completion, refactoring tools, debugger, etc. etc. etc… it's a pleasure to use. Just make sure you have a quick system, all the fancy features can take come CPU cycles and memory.

Visual Studio 2005 Express Edition (Free) - If you are getting started you don't need to buy the fully Visual Studio package yet, Visual Studio 2005 Express Edition is free and let's you do just about everything you can do in the full package.

Profiling Tools
CLR Profiler for .Net 2.0 - "The CLR Profiler includes a number of very useful views of the allocation profile, including a histogram of allocated types, allocation and call graphs, a time line showing GCs of various generations and the resulting state of the managed heap after those collections, and a call tree showing per-method allocations and assembly loads."

Debugging
Windbg - This is the debugger for Windows from Microsoft. It's command line driven, difficult to use, and give you exposure to everything. And, there are symbols and tools for .Net. Some tutorials to get started: .Net Framework Source Code and Debugging and A Windbg Tutorial.

Code Analysis Tools
Reflector for .Net - "Reflector is the class browser, explorer, analyzer and documentation viewer for .NET. Reflector allows to easily view, navigate, search, decompile and analyze .NET assemblies in C#, Visual Basic and IL." This one is especially helpful for getting insight into third party .Net libraries that you may be using in your projects.

DevMetrics by Anticipating Minds- This is a closed source but free tool for running basic analysis on your .Net projects. The application installs as a plugin to the Visual Studio environment as well as provides a console utility. The tool will provide you a breakdown of lines of code, cyclomatic complexity, and other metrics by solution, project, file, and object.

Unit Testing Tools
NUnit- NUnit is a tool for developing, maintaining, and running unit tests. By using NUnit to write test procedures (say, versus a console application) you can maintain tests for regression testing, easily execute all or a subset of tests, and get reports of results. Take a day to read the short documentation, I found it fit very well into my development pattern.

Documentation Tools
NDoc Code Documentation Generator for .Net - NDoc is a great tool for developing documentation files in various formats including HTML Help. If you are familiar with .Net development you'll know about the meta tags that are available when commenting code. The Microsoft compiler provides a flag to execute all of your in-code comments into an XML file. NDoc takes this XML file and makes it a user friendly readable and distributable format. By thoroughly documenting your code (as you should) NDoc will compile a valuable documentation file for future developers, testers, and other team members.

Compliance Tools
FxCop- "FxCop is a code analysis tool that checks .NET managed code assemblies for conformance to the Microsoft .NET Framework Design Guidelines." FxCop is a very in depth tool for analyzing source code for compliance. It was built by Microsoft for internal use to ensure uniform coding styles and standards across the company.

Build Tools
nAnt- "NAnt is a free .NET build tool." nAnt provides the ability to automate the complete build process. From integrating with source control for branching or tagging. To building the project. To copying files. To version control. Use nAnt to ensure all the steps to bring your software from code to test to delivery are consistent and complete.

Contiuous Integration Tools
CruiseControl - "CruiseControl is a framework for a continuous build process. It includes, but is not limited to, plugins for email notification, Ant, and various source control tools. A web interface is provided to view the details of the current and previous builds." Use CruiseControl especially if you have multiple developers checking in changes to ensure that your projects build successfully and pass unit tests all the time.

Source Control Tools
Subversion and TortoiseSVN- Subversion is an open source CVS replacement that many in the community find superior. TortoiseSVN is a great Windows client that provides Windows Explorer integration for managing your repositories. I've used SVN professionally and recommend it.

CVS and TortoiseCVS- CVS is a popular and free source control system. TortoiseCVS provides Windows Explorer integration for repository management. This is the system I use at home and you'll find most projects on the web use CVS as well.

Saturday, August 4, 2007

Frequently asked Differences in .Net

Collection of Differences which are frequently asked

Link got from http://dotnetguts.blogspot.com/2007/08/frequently-asked-differences-in-net.html

Thursday, July 26, 2007

C# Tips

1.How to Write debug string in C# ?

Using System.Diagnostics.Debug.Writeline() fn, we can write the debug string

2.How do we play default window sounds in C# ?
in .NET 2.0,

System.Media namespace is available. To play for example the classical beep sound, you could use the following code:

System.Media.SystemSounds.Beep.Play();
Similarly, you could play the “Question” sound with this code:
System.Media.SystemSounds.Question.Play();
The System.Media namespace is defined in System.dll, so there are no new DLLs you would need to add to your project’s references to use the above code.
3.What does the /target: command line option do in the C# compiler?
All the /target: options except module create .NET assemblies. Depending on the option, the compiler adds metadata for the operating system to use when loading the portable executable (PE) file and for the runtime to use in executing the contained assembly or module.
module creates a module. The metadata in the PE does not include a manifest. Module/s + manifest make an assembly - the smallest unit of deployment. Without the metadata in the manifest, there is little the runtime can do with a module.
library creates an assembly without an entry point, by setting the EntryPointToken of the PE's CLR header to 0. If you look at the IL, it does not contain the .entrypoint clause. The runtime cannot start an application if the assembly does not have an entry point.
exe creates an assembly with an entry point, but sets the Subsystem field of the PE header to 3 (Image runs in the Windows character subsystem - see the _IMAGE_OPTIONAL_HEADER structure in winnt.h). If you ILDASM the PE, you will see this as .subsystem 0x0003. The OS launches this as a console app.
winexe sets the Subsystem field to 2. (Image runs in the Windows GUI subsystem). The OS launches this as a GUI app.


4.What is the difference between const and static readonly?
The difference is that the value of a static readonly field is set at run time, and can thus be modified by the containing class, whereas the value of a const field is set to a compile time constant.
In the static readonly case, the containing class is allowed to modify it only
in the variable declaration (through a variable initializer)
in the static constructor (instance constructors, if it's not static)
static readonly is typically used if the type of the field is not allowed in a const declaration, or when the value is not known at compile time.
Instance readonly fields are also allowed.
Remember that for reference types, in both cases (static and instance) the readonly modifier only prevents you from assigning a new reference to the field. It specifically does not make immutable the object pointed to by the reference.
class Program
{
public static readonly Test test = new Test();
static void Main(string[] args)
{
test.Name = "Program";
test = new Test(); // Error: A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)
}
}
class Test
{
public string Name;
}
On the other hand, if Test were a value type, then assignment to test.Name would be an error.

5.How do I get and set Environment variables?
Use the System.Environment class.Specifically the GetEnvironmentVariable and SetEnvironmentVariable methods.Admitedly, this is not a question specific to C#, but it is one I have seen enough C# programmers ask, and the ability to set environment variables is new to the Whidbey release, as is the EnvironmentVariableTarget enumeration which lets you separately specify process, machine, and user.
Brad Abrams blogged on this way back at the start of this year, and followed up with a solution for pre-Whidbey users.


6.Preprocess Win32 Messages through Windows Forms
In the unmanaged world, it was quite common to intercept Win32 messages as they were plucked off the message queue. In that rare case in which you wish to do so from a managed Windows Forms application, your first step is to build a helper class which implements the IMessageFilter interface. The sole method, PreFilterMessage(), allows you to get at the underlying message ID, as well as the raw WPARAM and LPARAM data. By way of a simple example:
public class MyMessageFilter : IMessageFilter
{
public bool PreFilterMessage(ref Message m)
{
// Intercept the left mouse button down message.
if (m.Msg == 513)
{
MessageBox.Show("WM_LBUTTONDOWN is: " + m.Msg);
return true;
}
return false;
}
}
At this point you must register your helper class with the Application type:
public class mainForm : System.Windows.Forms.Form
{
private MyMessageFilter msgFliter = new MyMessageFilter();

public mainForm()
{
// Register message filter.
Application.AddMessageFilter(msgFliter);
}

}
At this point, your custom filter will be automatically consulted before the message makes its way to the registered event hander. Removing the filter can be accomplished using the (aptly named) static Application.RemoveMessageFilter() method.


7.Be aware of Wincv.exe :


When you install the .NET SDK / VS.NET, you are provided with numerous stand alone programming tools, one of which is named wincv.exe (Windows Class Viewer). Many developers are unaware of wincv.exe, as it is buried away under the C:\Program Files\Microsoft Visual Studio .NET 2003\SDK\v1.1\Bin subdirectory (by default).
This tool allows you to type in the name of a given type in the base class libraries and view the C# definition of the type. Mind you, wincv.exe will not show you the implementation logic, but you will be provided with a clean snapshot of the member definitions.


8.What is the equivalent to regsvr32 in .NET?
Where you once used Regsvr32 on unmanaged COM libraries, you will now use Regasm on managed .NET libraries.
“Regsvr32 is the command-line tool that registers .dll files as command components in the registry“
“Regasm.exe, the Assembly Registration tool that comes with the .NET SDK, reads the metadata within an assembly and adds the necessary entries to the registry, which allows COM clients to create .NET Framework classes transparently. Once a class is registered, any COM client can use it as though the class were a COM class. The class is registered only once, when the assembly is installed. Instances of classes within the assembly cannot be created from COM until they are actually registered.“ If you want to register an assembly programmatically, see the RegistrationServices class and ComRegisterFunctionAttribute

Wednesday, July 25, 2007

Effective C# mechanisms

Effective C# mechanisms:

1. Use 'as' and 'is' keywords instead of casting.

the ‘as' and ‘is' keywords instead of casting. It's true that those keywords let you test runtime type information without writing try / catch blocks or having exceptions thrown from your methods. It's also true that there are times when throwing an exception is the proper behavior when you find an unexpected type. But the performance overhead of exceptions is not the whole story with these two operators. The as and is operators perform run time type checking, ignoring any user defined conversion operators. The type checking operators behave differently than casts.
runtime performance as one justification for choosing among different language constructs, it's worth noting that very few Effective Items are justified strictly based on performance. The simple fact is that low-level optimizations aren't going to be universal. Low level language constructs will exhibit different performance characteristics between compiler versions, or in different usage scenarios. In short, low-level optimizations should not be performed without profiling and testing.

2.String Concatenation is expensive
string concatenation is an expensive operation. Whenever you write code that appears to modify the contents of a string, you are actually creating a new string object and leaving the old string object as garbage.

3.Checking the Length property is faster than an equality comparison
Some people have commented that this idiom:
if ( str.Length != 0 )
is preferable to this one:
if ( str != "" )
The normal justification is speed. People will tell you that checking the length of the string is faster than checking to see if two string are equal. That may be true, but I really doubt you'll see any measurable performance improvement.

4.String.Equal is better than == ( Refer gnana prakash anna's article)
5.Boxing and Unboxing are bad

This is true, boxing and unboxing are often associated with negative behaviors in your program. Too many times, the justification is performance. Yes, boxing and unboxing cause performance issues.

Tuesday, July 24, 2007

Generics

C# Generics :



Generics are a new feature in version 2.0 of the C# language and the common language runtime (CLR). Generics introduce to the .NET Framework the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code.
It is like a C++ template.



VC++.NET 2005 supports both generics and templates..NET generics differ from C++ templates.
difference is that specialization of a .NET generic class or method occurs at runtime whereas specialization occurs at compile time for a C++ template.

Key differences between generics and C++ templates:


Generics are generic until the types are substituted for them at runtime. Templates are specialized at compile time so they are not still parameterized types at runtime


The common language runtime specifically supports generics in MSIL. Because the runtime knows about generics, specific types can be substituted for generic types when referencing an assembly containing a generic type. Templates, in contrast, resolve into ordinary types at compile time and the resulting types may not be specialized in other assemblies.


Generics specialized in two different assemblies with the same type arguments are the same type. Templates specialized in two different assemblies with the same type arguments are considered by the runtime to be different types.


Generics are generated as a single piece of executable code which is used for all reference type arguments (this is not true for value types, which have a unique implementation per value type). The JIT compiler knows about generics and is able to optimize the code for the reference or value types that are used as type arguments. Templates generate separate runtime code for each specialization.


Generics do not allow non-type template parameters, such as





template C {}. Templates allow them.


Generics do not allow explicit specialization (that is, a custom implementation of a template for a specific type). Templates do.


Generics do not allow partial specialization (a custom implementation for a subset of the type arguments). Templates do.


Generics do not allow the type parameter to be used as the base class for the generic type. Templates do.


Generics do not allow type parameters to have default values. Templates do.


Templates support template-template parameters (e.g.

template class X> class MyClass ), but generics do not.

Monday, July 23, 2007

Cross thread operation failure in .NET 2.0

Cross thread operation failure in .NET 2.0 :

within the user created thread , if we tried to add or update the control, that will cause the Cross thread operation failure .

Description of the problem :

During Runtime, .NET CLR checks whether the control is accessed at the thread where it is created. otherwise .NET CLR will display the Cross thread operation failure.

For Example if we added the list box to the form, within the user created thread, if we add item to the list box , this will produce
cross thread operation failure error.

How to solve the cross thread operation failure problem :

All the controls are derived from Control class.

Thread Safety
Only the following members are safe for multithreaded operations: BeginInvoke, EndInvoke, Invoke, InvokeRequired, and CreateGraphics.

For other methods, the developer is responsible for thread safe.(The developer has to write code to make it as thread safe..)

How I solved the problem:
-------------------------------------

By calling the Invoke() method, I solved the problem...

Note : BeginInvoke() or Invoke() blocks the thread until it updates the data to the control.




delegate void UpdateControl(string text);

void UpdateList(string text)
{


if(listbox1.InvokeRequired)
{
UpdateControl updateCtl = new UpdateControl( UpdateList);
listbox1.Invoke(updateCtl, text);
}
else
{
listbox1.Items.Add(text); // Add item to the list box...
}
}


void ThreadProc () // Cross thread's operation failure
{
UpdateList( "Sundar");
}



InvokeRequired member is true, if the cross thread operation execution takes place. ( this will be done by the framework by comparing the thread instance)




Full sample application with code:



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace CrossThreadInvoke
{
public partial class Form1 : Form
{

private Thread thread1 = null;
private ThreadStart threadStart1 = null;
delegate void UpdateControl (string text);


public Form1()
{
InitializeComponent();
threadStart1 = new ThreadStart(ThreadProcedure);
thread1 = new Thread(threadStart1);


}
private void UpdateList(string text)
{
if (listBox1.InvokeRequired)
{
UpdateControl m_UpdateControl = new UpdateControl(UpdateList);
listBox1.Invoke(m_UpdateControl, text);
}
else
{
listBox1.Items.Add(text);
}
}

private void ThreadProcedure()
{
int i = 0;
while (true)
{
if (i > 10)
{
break;
}

UpdateList("Sundar");
i++;
}

thread1.Abort();
}
private void btnStart_Click(object sender, EventArgs e)
{
thread1.Start();
}

private void btnStop_Click(object sender, EventArgs e)
{
thread1.Abort();
}
}
}


BeginInvoke() :

it is working in the same way as Invoke() fn...

Check the following sample application :


BeginInvoke() Sample application :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;


namespace CrossThread
{
public partial class Form1 : Form
{
private Thread thread1 = null;
private ThreadStart threadStart1 = null;

public delegate void UpdateList(string text);
public UpdateList m_UpdateList = null;



public Form1()
{
InitializeComponent();
m_UpdateList += new UpdateList(SetToList1);
threadStart1 = new ThreadStart(AddToList1);
thread1 = new Thread(threadStart1);

}


public void SetToList1(string text)
{
listBox1.Items.Add(text);
}


private void AddToList1()
{
try
{
int i = 10;
while (true)
{
if (i <= 0) break;
listBox1.BeginInvoke(m_UpdateList, "sundar");
i--;
Thread.Sleep(1000);
}

}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());

}
}



Invoke() fns are thread safe.



In case of Invoke() fn what happens ...


void UpdateList(string text)
{
if( listbox1.InvokeRequired )
{
UpdateControl m_UpdateControl = new UpdateControl(UpdateList);
listbox1.Invoke( m_UpdateControl, text);
}
else
{
listbox1.Items.Add( text);
}
}


How this code works ...

Main thread is available to the C# application until we closes the application.
Application.Run() method in C# begins running a standard application message loop in the Form's main thread.
Each and Every thread has its own message queue for messages. if any event occurs in the thread will be added to the corresponding thread's message queue.


while we are accesing the listbox from cross thread, the thread instance is checked ...

For Cross thread, InvokeRequired field is set to true.


Invoke() fn executes a delegate on the thread that owns the control's underlying window handle.
The delegate is executed in the thread which the control is created . Until the completion of the delegate execution,
the current thread is blocked .

This is also same to BeginInvoke() fn . At which scenario we will use Invoke() and BeginInvoke()...

Normally for UI update we will use Invoke() method.
For UI data updation, we will use BeginInvoke() method.

For Example Updating the text to the list box we can use BeginInvoke() method.
For Example adding controls to the tab controls we may go for Invoke() fn. BeginInvoke() fn execution is much faster than Invoke() fn.

Friday, July 20, 2007

Difference between Delegate and Delegate With event

Is there any difference between the delegate and delegate with event ?...

Yes... See the sample



delegate void UpdateControl( string text);
UpdateControl m_UpdateControl = null;
private event UpdateControl m_EventUpdateControl = null;


m_UpdateControl += new UpdateControl( UpdateListCtrl);
m_EventUpdateControl += new UpdateControl( UpdateListCtrl);

private void UpdateListCtrl()
{
listSent.items.Add("Test" + listSent.items.count);
}




we can create the object as follows :

m_UpdateControl = new UpdateControl(UpdateListCtrl); // will work properly

But the following code will not work properly...

m_EventUpdateControl = new UpdateControl(UpdateListCtrl);

we have to change it as

m_EventUpdateControl += new UpdateControl(UpdateListCtrl);

This implies...
we can set the delegate object as null as follows in anywhere like during initialization or within any fn.


m_UpdateControl = null;


But for Event with delegate object, we will not be able to initialize it as null , it affects the other client's delegates also.

m_EventUpdateControl = null; // Exception : we can initialize null for the event with delegate object during initialization.


what it means is that if we use the event keyword no client class can set it to null. This is very important. Multiple clients can use the same delegate. After multiple client have added a function to listen to the callback of the delegate. But now one of the client sets the delegate to null or uses the = sign to add a new call back. This means that the previous invocation list will not be used any more. Hence all the previous client will not get any of the callback even if they have registered for the call back.

Hence we can say that the even keyword adds a layer of protection on the instance of the delegate. The protection prevents

any client to reset the delegate invocation list. They can only add or remove the target from the invocation list.

Tuesday, July 17, 2007

Difference between == and .Equals Method

What is Difference between == and .Equals() Method?

For Value Type: == and .Equals() method usually compare two objects by value.

For Value Type: == and .Equals() method usually compare two objects by value.

For Example:

int x = 10;

int y = 10;

Console.WriteLine( x == y);

Console.WriteLine(x.Equals(y));


Will display:

True

True




For Reference Type: == performs an identity comparison, i.e. it will only return true if both references point to the same object. While Equals() method is expected to perform a value comparison, i.e. it will return true if the references point to objects that are equivalent.

For Example:


StringBuilder s1 = new StringBuilder("Yes");

StringBuilder s2 = new StringBuilder("Yes");

Console.WriteLine (s1 == s2);

Console.WriteLine(s1.Equals(s2));


Will display:

False

True


In above example, s1 and s2 are different objects hence "==" returns false, but they are equivalent hence "Equals()" method returns true. Remember there is an exception of this rule, i.e. when you use "==" operator with string class it compares value rather than identity.


When to use "==" operator and when to use ".Equals()" method?

For value comparison, with Value Tyep use "==" operator and use "Equals()" method while performing value comparison with Reference Type.

Thanks: http://dotnetguts.blogspot.com/2007/07/difference-between-and-equals-method.html

Sunday, July 15, 2007

Code Snippet - Email Validation using Reg. Exp (C#)

public

bool IsEmail(string inputEmail)

{

string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +

@"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +

@".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";

Regex re = new Regex(strRegex);

if (re.IsMatch(inputEmail))

return (true);

else

return (false);

}