C#


There are some things which are seemingly simple but are difficult to get done for the first time at least. This is one of them.

The other day I had to get a Stream from the String I had. Though it was apparently easy, it took me quite a while to figure it out. Nevertheless here’s what I did:

MemoryStream myStream = new MemoryStream(ASCIIEncoding.Default.GetBytes("My String"));

Recently I had a requirement where I had to create an XML file without any definitive structure but from a Class file. I had to write a tag for each class and a child property for each property.

Then instead of going for a primitive method of using the XML Document class, I went for LINQ to XML. The XElement makes life very easy when writing an XML. I just had to write 2 recursive methods to write the entire XML file.

This article helped a lot.

We do not have a built in split button in .net Framework. The work around is use tool strip split button which is not that useful in aesthetic perspective.

This is very good article where the author extended the standard Button control and modified it into a split button.

Modifying a Type at runtime is always difficult.

Requirement: Object must be assigned to a PropertyGrid. To expand the nested complex types in the Object, TypeConvertor attributes should be added to the properties of the type. Type should be modified not be modified at design time.

Solution: The PropertyGrid does not expand the nested complex types of an object assigned to it, if the complex type is a user-defined object. We need to add TypeConverterAttribute(typeof(ExpandableObjectConverter) to the user-defined types. Since I cannot modify the user-defined type at design time, it was not a feasible option. That leaves me with two alternatives:

Alternative 1: Tweak the Property Grid to show the nested Complex types. Given the Complexity of Property Grid and the time constraint to solve the problem, I had to go to the second alternative.

Alternative 2: After searching  lot on the internet, I stumbled here. The way to achieve the task is to bluff the Property Grid. Before you create the object, add the attributes to the properties of the type at runtime using COM (not Reflection). What you do is tell the Property Grid that the Type you used has the Attributes required for the former display the nested complex types.

The Code goes something like this:

AttributeCollection oldAttributes = TypeDescriptor.GetAttributes(type); 
Attribute[] newAttributes = new Attribute[oldAttributes.Count + 1]; 
oldAttributes.CopyTo(newAttributes, 0); 
newAttributes[oldAttributes.Count] = new TypeConverterAttribute(typeof(ExpandableObjectConverter)); 
TypeDescriptor.AddAttributes(type, newAttributes);

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Every application has a configuration file and you want to have some keys in that file which are

  • application specific
  • easily accessible in the application
  • have read and write operations

Read the keys with the following code:

System.Configuration.ConfigurationSettings.AppSettings["keyname"];

I am working lately a lot on Reflection and WCF. So there will be quite a few posts on around those two.

This is one relates to the former category.

Problem: You want to create a Combo Box at runtime and the items to be included in the Combo Box should be read from an enum.

Solution: Read the Enumeration at runtime and fill the items of the combo box with them.

First get all the values from the Enumeration:

String[] names = System.Enum.GetNames(typeof(enumToRead));

enumToRead is the Enum which you have to read the names from.

Now, iterating through each of the names, add it to the Combo Box:

foreach (string name in lstProvider)
{
   cboxMyComboBox.Items.Add(name);
}

You can similarly get all the values in the enum by:

Array enumVal = Enum.GetValues(typeof(enumToRead)) ;

To retrieve the IP Address of the Machine on which the code is executed, you can use the following code:

 

string hostName = System.Net.Dns.GetHostName(); //get the name of the computer…

//gets the Ipaddress of the machine…

string IPAdd = System.Net.Dns.GetHostEntry(hostName ).AddressList[0].ToString();  

To start a thread with a method having parameters, one cannot use the traditional way of starting a thread.

The best way is to use a Anonymous Delegate to start a thread.

Here’s the sample:

MyParameteredMethod is my method which accepts 3 parameters. I wish to start this method in a new thread.

MyParameteredMethod is my paramet
ThreadStart ts = delegate() { MyParameteredMethod(param1, param2, param3); };
Thread t = new Thread(ts);
t.Start();

There are different modifiers which decide the visibility of the types or members.

They are:

Modifier

Applies To Description
public Any types or members The item is visible to any other code.
protected Any member of a type, also any nested type The item is visible only to any derived type.
internal Any member of a type, also any nested type The item is visible only within its containing assembly.
private Any types or members The item is visible only inside the type to which it belongs.
protected internal Any member of a type, also any nested type The item is visible to any code within its containing assembly and also to any code inside a derived type.

Some other modifiers are:

Modifier

Applies To Description
public Any types or members The item is visible to any other code.
protected Any member of a type, also any nested type The item is visible only to any derived type.
internal Any member of a type, also any nested type The item is visible only within its containing assembly.
private Any types or members The item is visible only inside the type to which it belongs.
protected internal Any member of a type, also any nested type The item is visible to any code within its containing assembly and also to any code inside a derived type.

There are two types of inheritence implemented in C#. Implementation Inheritence and Interface Inheritence.

Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and functions. With implementation inheritance, a derived type adopts the base type’s implementation of each function, unless it is indicated in the definition of the derived type that a function implementation is to be overridden. This type of inheritance is most useful when you need to add functionality to an existing type, or where a number of related types share a significant amount of common functionality.

Interface inheritance means that a type inherits only the signatures of the functions but does not inherit any implementations. This type of inheritance is most useful when you want to specify that a type makes certain features available. Interface inheritance is often regarded as providing a contract: By deriving from an interface, a type is guaranteed to provide certain functionality to clients.

Imp: C# doesnot implement Multiple Inheritence i.e. you cannot inherit a class from more than one class.

By declaring a base class function as virtual, you allow the function to be overridden in any derived classes.

class MyBaseClass
{
   public virtual string VirtualMethod()
   {
      return “This method is virtual and defined in MyBaseClass and can be overridden in                   derievd class”;
   }
}

You use the override keyword when you write a new implementation of the virtual method in the derieved class.

public override string VirtualMethod() //this is the method which is overriden.

Neither member fields nor static functions can be declared as virtual.

Hiding Methods

If a method with the same signature is declared in both base and derived classes, but the methods are not declared as virtual and override, respectively, then the derived class version is said to hide the base class version.In these situations, C# generates a compilation warning. That reminds you to use the new keyword to declare that you intend to hide a method.

you can use the base.<MethodName>() syntax to call any method in the base class .

C# allows both classes and functions to be declared as abstract. An abstract class cannot be instantiated, whereas an abstract function does not have an implementation, and must be overridden in any non-abstract derived class. Obviously, an abstract function is automatically virtual (although you don’t need to supply the virtual keyword; doing so results in a syntax error).

C# allows classes and methods to be declared as sealed. In the case of a class, this means that you can’t inherit from that class. In the case of a method, this means that you can’t override that method.

Constructors in the hierarchy

If all the classes in the hierarchy have only default constructors then when u instantiate a class the control goes to the constructor of its immediate base class from there it goes to its immediate base class…like that till it reaches System.Object. Since System.Object doesnot have any base class…its constructor is executed…then its next derieved class’ cons is exec…till it reaches the cons of the class to be instantiated.

When you write your own constructors…stick to this principle.The base and this keywords are the only keywords allowed in the line that calls another constructor. Anything else causes a compilation error. Also note that only one other constructor can be specified.

We’ll take an example to understand this:

We have class called Employee it just has a field indicating the EmpId

class Employee
{
      private string empId;
      public Employee()
     {
      }
}

Then you have a class called ContractEmployee which is inherited from Employee and has an extra field of number of contract months.
class ContractEmployee: Employee
{
       private int contractMonths;
       public ContractEmployee():base()
      {
      }
}

In the above case when the class ContractEmployee is instantiated then the default cons of its base class is called and goes upto Object class. If you want to instantiate the employee field with employee id i.e if the user has to produce the employee id of the new emp while creating the class itself then the constructor of the Employee class takes a parameter and takes the following form

class Employee
{
      private string empId;
      public Employee(string id)
     {
          this.empId = id;
     }
}

Now when you instantiate the derieved class i.e the ContractEmployee class then you have to supply name to the emp…but that field is a private member of the base class. So what you have is sth like this:

class ContractEmployee: Employee
{
       private int contractMonths;
       public ContractEmployee(string id):base(id)
      {
      }
}

The derieved class has no way to implement this but the base class can do that so what the former does is to pass on the parameter to the base class cons.

Now the req is that the emp who referred to the conractemp should be saved in a field of referrer.

class ContractEmployee: Employee
{
       private int contractMonths;
       private string referrer;
       public ContractEmployee(string id,string refr):base(id)
      {
            this.referrer = refr
      }
}

But there may be some contract emp who have no referrers for them there would be no referrers. For them you should have a one parameter cons.Note how this is implemented….the derieved class now has two constructors with two parameters.

class ContractEmployee: Employee
{
       private int contractMonths;
       private string referrer;
       public ContractEmployee(string id,string refr):base(id)
      {
            this.referrer = refr
      }
     public ContractEmployee(string id):this(id,”none”)
      {      
      }

}

thi is how more than one constructors are implemented.When a contract emp with no ref is instantiated then cons with one param is called which in turns call the cons with 2 params giving the referrer as “none” then the base classes single param cons is called.

Next Page »