Notes eMeroo(Some TechTips);

December 22, 2008

Tips and Tricks for C# Constructors

Filed under: C# — Amira @ 3:56 pm

This Post From My Old Blog

Hello, Here I’ll tell you some notes about constructors and some tricks that you may face while using constructors.
* Constructors never define return value (that what distinguish constructor from method).

* If you didn’t define a constructor in your class, it will be automatically supplied with the default constructor. But if you defined a constructor with parameters, the supplied default constructor will be removed and you won’t be able to use it until you explicitly define it in your class.

* If you defined your class as internal and a constructor inside it as public, so you can’t new use it in another assembly. Although the constructor is public, but the class is internal (accessed only inside the assembly that define it).

That’s a class definition in an assembly named Constructors

using System;

namespace Constructors

{

class parent

{

public parent()

{ Console.WriteLine(“Hello”); }

}

}

Try to use parent class in another assembly. Create console application and make reference to Constructors.dll

using System;
using Constructors;

namespace usingConstructor
{
class Program
{
static void Main(string[] args)
{
parent p =
new parent();
}
}
}

You’ll receive error.

* The default access modifier for the constructor is private (like methods).

* If a constructor defined as private, you can’t instanciate it outside the class. And also you can’t define a child class inherit from parent class.Why???!!

Have a look at this code

namespace Constructors

{

public class parent

{

parent()

{ Console.WriteLine(“Hello”); }

}

public class child:parent

{

}

}

When you define child class inherit from parent class, the child class not only implicitly define default constructor but also this default constructor is implicitly call the default constructor of the parent class.

And here in child class, there isn’t constructor defined explicitly, then it will be implicitly supplied with the default constructor. This default constructor will call the default constructor of the parent class. The error will be raised at this step, because the default constructor in parent class is private, so child class can’t see it.

* Constructors can take any access modifier. Protected access modifier with constructor allow child class to inherit from parent class without any errors. But if you defined constructor as protected, you can’t access it through object variable. Such as protected access modifier with methods. As I described it before.

So if you try to write this line of code inside child class, you’ll receive an error

parent p = new parent();

* Now after defining parent class as public and its constructor as protected, try to create an object from child class inside Main in the console application that we created miniuts ago.

child c = new child();

the output is : Hello

* The first statement is executed inside the constructor is calling the default constructor of the base class(be aware that if your class didn’t explicitly inherit from a base class, your class will implicitly inherit from object class. And then every constructor will call object’s default constructor).

Try this

namespace Constructors

{

public class parent

{

protected parent()

{ Console.Write(“Hello,”); }

}

public class child:parent

{

public child(){}

public child(string yourName)

{

Console.WriteLine(yourName);

}

}

}

And inside the Main, try this

static void Main(string[] args)

{

child c = new child(“Amira”);

Console.WriteLine();

child c1 = new child();

Console.Read();

}

-First line in Main, I created an object from child with a string argument “Amira”

Here it will invoke the constructor of child class that take a string and write it. But before executing this statement inside child’s constructor, it’ll invode the parent’s default constructor(which write Hello,) so the result of that statement will be Hello, Amira

-Second line in Main, insert new line

-Third line in Main: I created another object from child class, but here it will invoke the custom default constructor with no argument. This constructor as I defined do nothing except the implicit call for parent’s default constructor. So the output will be Hello,

* If parent class has no default constructor, then when the constructors inside child class try to call the parent’s default constructor, they wont find it, you will receive error. Try to change the definion of the constructor inside parent class

public class parent

{

protected parent(string s)

{ Console.Write(“Hello,”); }

}

Here the default constructor is removed, and you’ll receive an error in that statement inside child class

public child(){} //error

* As I said before, the first statement is executed at child’s constructor is thr implicit call to paren’s default constructor. You can explicitly invoke the parent’s constructor in child’s constructors through base keyword (and the explicit call allow you to invoke any constructor defined at parent class), and that explicit call will be also the first statement executed when you instanciate the child class. If you supported child constructor with explicit call, the implicit one will be removed.

Try this

namespace Constructors

{

public class parent

{

protected parent(string str)

{ Console.Write(“Hello,” + str); }

}

public class child:parent

{

public child()

: base(“Amira”)

{ }

public child(string yourName)

: base(yourName)

{ }

}

}

Try again what we wrote in main the output will be

Hello, Amira
Hello, Amira

* Also you can make explicit call to a constructor that is defined inside the class through this keyword(that is instead of the explicitly call to parent’s constructor or instead of the implicitly call to parent’s default constructor).

So change child class definition to

public class child:parent
{
public child()
: base(“Amira”)
{ }
public child(string yourName):this()
{ Console.WriteLine(“\nBye”); }
}

Run the console application again, the output will be

Hello, Amira
Bye
Hello, Amira

* you can overload the constructor, the code you wrote before, you overloded child’s custom default constructor with an overloaded constructor with one parameter.

* Constructors can be defined as static, but you allowed to define only a single static constructor. And this static constructor doesn’t take any access modifier and also doesn’t take any parameters.

* Static constructor executes only one time, and executes before the other constructors.

Here inside StaticConstructor class, I defined static constructor which prints a message to inform the user when the static constructor is invoked and also to initialize static field (y)

public class StaticConstrucor

{

public int x;

public static int y;

static StaticConstrucor()

{

Console.WriteLine(“static constructor is invoked now”);

y = 2;

}

public StaticConstrucor()

{

Console.WriteLine(“x={0} and y={1}”,x,y);

}

public StaticConstrucor(int x)

{

this.x = x;

Console.WriteLine(“x={0} and y={1}”, x, y);

}

}

* The runtime invokes the static constructor when it creates an instance of the class or before accessing the first static member invoked by the caller. Try this snippet of code inside the Main method

StaticConstrucor s = new StaticConstrucor();
StaticConstrucor s1 = new StaticConstrucor(3);
StaticConstrucor.y = 9;
StaticConstrucor s2 = new StaticConstrucor();

Here the static constructor invoked only once when I instanciated StaticConstructor class. So the output will be

static constructor is invoked now
x=0 and y=2
x=3 and y=2
x=0 and y=9

Also it can be invoked automatically before invoking the static member y, try only this statement
Console.WriteLine(StaticConstrucor.y);

Here the output will be

static constructor is invoked now
2

That all what I remembered about constructors. I wish I covered this topic well, and I hope that helps :D

Amira

How to Copy all Photos in a tree of Directories?

Filed under: C# — Amira @ 3:54 pm

This Post From My Old Blog
I have a Directory named photo,this directory organizes my all my photos. It contains set of subdirectories (such as Stars, Family, Work, …etc) and inside each subdirectory there are other subdirectories, for example in Family directory I have some photos in addition to 2 directories (Father’s Family and Mother’s Family) and inside each one of them there are some other directories and so on.

How to get a copy of all these photos inside the directory called photo and all photos inside the tree of its subdirectories up to the 3rd degree of photo directory’s depth ??!

   1: using System;
   2: using System.IO;
   3:
   4: namespace CopyPhotos
   5: {
   6:     class Program
   7:     {
   8:         public static int i = 0;
   9:         //create new directory in dirve D
  10:         static DirectoryInfo dir = new DirectoryInfo(@"D:\MyPhotos");
  11:
  12:         //Generate a string represents the full path for each copied photo
  13:         public static string GenerateImgName()
  14:         {
  15:             string name = "IMG" + i++.ToString();
  16:             string fullPath = @dir.FullName + @"\" + name + ".jpg";
  17:             return fullPath;
  18:         }
  19:
  20:         //copy each jpg photo in specefied directory
  21:         public static void CopyPhotosInDir(DirectoryInfo d)
  22:         {
  23:             foreach (FileInfo f in d.GetFiles("*.jpg"))
  24:                 f.CopyTo(GenerateImgName());
  25:         }
  26:
  27:         //copy each photo in the directory D:\Library\Photo and
  28:         //also copy each photo in each subdirectory up to the 3rd depth of subdirectories
  29:         public static void CopyAllPhotosInRootDir()
  30:         {
  31:             DirectoryInfo di = new DirectoryInfo(@"D:\Library\Photo");
  32:             CopyPhotosInDir(di);
  33:             foreach (DirectoryInfo d1 in di.GetDirectories())
  34:             {
  35:                 CopyPhotosInDir(d1);
  36:                 foreach (DirectoryInfo d2 in d1.GetDirectories())
  37:                 {
  38:                     CopyPhotosInDir(d2);
  39:                     foreach (DirectoryInfo d3 in d2.GetDirectories())
  40:                         CopyPhotosInDir(d3);
  41:                 }//end second foreach
  42:             }//end first foreach
  43:         }//end CopyAllPhotosInRootDir
  44:
  45:         static void Main(string[] args)
  46:         {
  47:             //create the directory D:\MyPhotos
  48:             dir.Create();
  49:
  50:             //copy all photos inside D:\Library\photo Directory
  51:             CopyAllPhotosInRootDir();
  52:         }
  53:     }
  54: }

this executable assembly copies all the jpg files to D:\MyPhotos, you can copy all photos by changing Line 23 to

foreach (FileInfo f in d.GetFiles())
Downlod the program
hope this helps, smile_regular

Amira

Some C# Tricks of Method’s Access Modifier

Filed under: C# — Amira @ 3:51 pm

This Post From My Old Blog

Here I constructed a class called BaseClass that has some methods with different access modifier. Then I created another class named InheritedClass that inherits from BaseClass. InheritedClass override some of BaseClass methods and in InheritedClass’s Main method, try to access all of the methods(in both classes) using a variety of objects. Try to concentrate and follow up the comments placed inside the program, I hope it help.


using System;

using System.Collections.Generic;

using System.Text;


namespace AccessModifier

{

class BaseClass

{

protected static string ProtectedStatic()

{

return “protected static method in BaseClass”;

}


protected string ProtectedNonStatic()

{

return “protected non static method in BaseClass”;

}


protected virtual string ProtectedVirtual()

{

return “protected virtual method in BaseClass”;

}


public virtual string PublicVirtual()

{

return “public virtual method in BaseClass”;

}

}


class InheritedClass : BaseClass

{


protected override string ProtectedVirtual()

{

return “override Protected virtual”;

}


public override string PublicVirtual()

{

return “override Public Virtual”;

}


static void Main(string[] args)

{

//Now I’ll create 3 objects,

BaseClass bc = new BaseClass(); //bc stands for BaseClass object

BaseClass bcic = new InheritedClass(); //bcic stands for BaseClass object created polymorphically

InheritedClass ic = new InheritedClass(); //ic stands for InheritedClass object



Console.WriteLine(“\n*********Workin on ProtectedVirtual method**********”);


//???? If you wanna invoke what’s typed inside the overriden method of ProtectedVirtual????//

//Easily you can do so, just call the method over an object of the InheritedClass

Console.WriteLine(ic.ProtectedVirtual()); //output–> override Protected virtual


//?????okay,Now I want to call the protectedvirtual of BaseClass here What Should I do?????//


/*First: Try to call it over a polymorphic object after casting it to InheretedClass

,..What’ll happen?? Note:(without casting you’ll recieve error)*/

Console.WriteLine(((InheritedClass)bcic).ProtectedVirtual()); //OUTPUT –> override Protected virtual

Console.WriteLine(bcic.ProtectedVirtual());//error without casting



/*Second: Try to call it over BaseClass object after casting it to InheritedClass

…Guess what’ll happen?? Note:(without casting you’ll recieve error)*/

Console.WriteLine(((InheritedClass)bc).ProtectedVirtual()); //invalid cast exception

Console.WriteLine(bc.ProtectedVirtual()); //error without casting


/*Third: Try to call the protectedVirtual of BaseClass using the base keyword,

but you doesn’t define protectedVirtual as static so you can’t invoke it in static method

and also you can’t define the virtual method as static*/

Console.WriteLine(base.ProtectedVirtual()); //error using base keyword


Console.WriteLine(“\n*********Workin on ProtectedStatic method**********”);


/*Finally: So you can’t invoke the ProtectedVirtual method(or any protected method) of BaseClass

over an BaseClass’s object that’s defined inside InheritedClass

So, What should I try ?!!!!!

Instead, you have two solutions.*/


/*1–>Either, you can define the protected method as static

and then invoke it through the class level not the object level

Try to invoke the ProtectedStatic method of BaseClass here over the class level, it’ll succeed*/

Console.WriteLine(InheritedClass.ProtectedStatic()); //OUTPUT –> protected static method in BaseClass

Console.WriteLine(BaseClass.ProtectedStatic()); //it also output –>protected static method in BaseClass

/*Note: static method work through class level not the object level, so of you try to

invoke ProtectedStatic method over BaseClass or InheritedClass objects, you’ll recieve error*/

Console.WriteLine(bc.ProtectedStatic()); //error

Console.WriteLine(ic.ProtectedStatic()); //error

Console.WriteLine(bcic.ProtectedStatic()); //error


/* 2–>OR, you can define the method in the BaseClass as public virtual and override it

inside InheritedClass as public, so you can invoke both methods of the BaseClass and InheritedClass

So Now,Try all the statements that are failed using the ProtectedVirtual method but over PublicVirtual*/


Console.WriteLine(“\n*********Workin on PublicVirtual method**********”);

Console.WriteLine(bcic.PublicVirtual()); //OUTPUT–> override Public Virtual

Console.WriteLine(((InheritedClass)bcic).PublicVirtual()); //OUTPUT –> override Public Virtual

Console.WriteLine(bc.PublicVirtual()); // OUTPUT –> public virtual method in BaseClass

Console.WriteLine(((InheritedClass)bc).PublicVirtual()); //invalid cast Exception

Console.WriteLine(base.PublicVirtual()); //error while invoking it inside static method


Console.WriteLine(“\n*********Workin on ProtectedNonStatic method**********”);


//protected method in BaseClass can’t be accessed over BaseClass object

Console.WriteLine(bc.ProtectedNonStatic()); //error


//you can’t cast BaseClass object to InheritedClass

Console.WriteLine(((InheritedClass)bc).ProtectedNonStatic()); //invalid cast exception


//protected method in BaseClass can’t be accessed over BaseClass object,even if it

//has reference to InheritedClass object

Console.WriteLine(bcic.ProtectedNonStatic()); //error



/*you can invoke protected method in BaseClass over InheritedClass object

because the InheritedClass inherit ProtectedNonStatic method implicitly*/

Console.WriteLine(ic.ProtectedNonStatic()); //OUTPUT –> protected non static method in BaseClass


/*Also,you can invoke ProtectedNonStatic method over a polymorphic object(bcic has reference to

InheritedClass in the heap), here you’ll cast it to InheritedClass, so it inherit the method implicitly*/

Console.WriteLine(((InheritedClass)bcic).ProtectedNonStatic()); //OUTPUT–> protected non static method in BaseClass


Console.Read();


}

}

}

THIS is the OUTPUT

*********Workin on ProtectedVirtual method**********

override Protected virtual

override Protected virtual

*********Workin on PublicStatic method**********

protected static method in BaseClass

protected static method in BaseClass

*********Workin on PublicVirtual method**********

override Public Virtual

override Public Virtual

public virtual method in BaseClass

*********Workin on ProtectedNonStatic method**********

protected non static method in BaseClass

protected non static method in BaseClass

Amira

Theme: Rubric. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.