IT SOLUTIONS
Your full service technology partner! 
-Collapse +Expand
C#
Search C# Group:

Advanced
-Collapse +Expand C# To/From
To/FromCODEGuides
-Collapse +Expand C# Study Test
PRESTWOODCERTIFIED
-Collapse +Expand C# Store
PRESTWOODSTORE

Prestwood eMagazine

October Edition
Subscribe now! It's Free!
Enter your email:

   ► KBProgrammingC#OOP   Print This     
  From the March 2016 Issue of Prestwood eMag
 
C# OOP:
C# Constructors (Use class name)
 
Posted 15 years ago on 1/18/2009 and updated 2/27/2009
C# Code Snippet:
 A flashcard from our C# Flashcards Library
 A code snippet from our C# Code Snippets Page

KB101819

General Info: Class Constructor

Constructors are called when you instantiate an object from a class. This is where you can initialize variables and put code you wish executed each time the class is created. When you initially set the member fields and properties of an object, you are initializing the state of the object. The state of an object is the values of all it's member fields and properties at a given time.

Languages Focus: Constructor

What is the syntax? Can you overload constructors? Is a special method name reserved for constructors?

C# Constructors

In C#, a constructor is called whenever a class or struct is created. A constructor is a method with the same name as the class with no return value and you can overload the constructor.

If you do not create a constructor, C# will create an implicit constructor that initializes all member fields to their default values.

Constructors can execute at two different times. Static constructors are executed by the CLR before any objects are instantiated. Regular constructors are executed when you create an object.

Syntax Example:
public class Cyborg
{
public string CyborgName;
  
  //Constructor.
  public Cyborg(string pName)
{
CyborgName = pName;
}
}

C# Constructor Details

  • Use class name. A method with the same name as the class.
  • No return value.
  • Overloadable. You can overload your constructors.
  • Optional. When you create classes, you do not have to create a class constructor. If you do not, the constructor for the parent class is called.
  • Static Constructors. You can make a constructor static (class member fields are initialized by the CLR prior to any object instantiations).

Overloading C# Constructors

You can overload a constructor with various parameters that initialize object instances to various states.

public class Cyborg
  {
    public string CyborgName;
  
    //Constructor with no params.
    public Cyborg() { }
  
    //Constructor with a parameter.
    public Cyborg(string pName)
    {
      CyborgName = pName;
    }
  }

Working WinForms Example

The following demonstrates using a finalizer and System.GC.Collect(). I placed a MessageBox.Show() in the finalizer so you can see when it is called. The finalizer gets called when the compiler needs to free resources or you call System.GC.Collect(). You'll notice that although the local variable in the button click event falls out of scope, your finalizer is not called until either you close the form or click the button that calls System.GC.Collect().

Create a form with two buttons and add code as follows:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace CR_Constructor
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
      //Use class calling no parameter constructor.
      Cyborg MyRobot1 = new Cyborg();
      MyRobot1.CyborgName = "John";
      MessageBox.Show("My robot's name is " + MyRobot1.CyborgName);
  
      //Use the class calling an overloaded 
      //constructor with a single parameter.
      Cyborg MyRobot2 = new Cyborg("Cameron");
      MessageBox.Show("My robot's name is " + MyRobot2.CyborgName);
    }
  }
  
  public class Cyborg
  {
    public string CyborgName;
  
    //Constructor with no params.
    public Cyborg() { }
  
    //Constructor with a parameter.
    public Cyborg(string pName)
    {
      CyborgName = pName;
    }
  }

Static Constructors

You can make a constructor static. With a static constructor, the CLR initializes the static class member fields prior to any object instantiations. You can have only one static constructor with no parameters.

public class Cyborg
{
  //Executes once per program.
  static Cyborg() { }
}

You can have a static constructor and a regular constructor. The static constructor executes once prior to any object instantiations then the regular constructor executes every time you instantiate an object. At first glance of the following code, you might think it will not compile because it breaks the rules of overloading. However, it doesn't break any rules because each method is called at a different time.

public class Cyborg
{
  public string CyborgName;
  
  //Executes once per program. Notice no access modifier.
  static Cyborg() { }
  //Executes once per object instantiation.
  public Cyborg() { }
}

More Info

Code:  C# Finalizer (~ClassName)
Definition:  Class Constructor

Comments

0 Comments.
Share a thought or comment...
 
Write a Comment...
...
Sign in...

If you are a member, Sign In. Or, you can Create a Free account now.


Anonymous Post (text-only, no HTML):

Enter your name and security key.

Your Name:
Security key = P157A1
Enter key:
Code Contributed By Mike Prestwood:

Mike Prestwood is a drummer, an author, and creator of the PrestwoodBoards online community. He is the President & CEO of Prestwood IT Solutions. Prestwood IT provides Coding, Website, and Computer Tech services. Mike has authored 6 computer books and over 1,200 articles. As a drummer, he maintains play-drums.com and has authored 3 drum books. If you have a project you wish to discuss with Mike, you can send him a private message through his PrestwoodBoards home page or call him 9AM to 4PM PST at 916-726-5675 x205.

Visit Profile


Linked Certification Question(s)

The following are practice certification questions with answers highlighted. These questions were prepared by Mike Prestwood and are intended to stress an important aspect of this KB post. All our practice questions are intended to prepare you generally for passing any certification test as well as prepare you for professional work.

Beginner

1 Beginner Level Question

Question #1: True or False?

If you do not create a developer defined constructor, C# creates an implicit constructor and initializes all member fields to their default values.

Answer:
  • True
  • False
  • Intermediate

    1 Intermediate Level Question

    Question #2: Multiple Choice

    The method name of a constructor is?

    Answer:
    1. 

    A method named New.

    2. 

    An unnamed method that uses the constructor keyword.

    3. 

    A method with the same name as the class and with no return value.

    4. 

    Any method name that uses the constructor keyword.

    Advanced

    1 Advanced Level Question

    Question #3: True or False?

    You can overload static constructors.

    Answer:
  • True
  • False

  •  KB Article #101819 Counter
    19579
    Since 1/18/2009
    Go ahead!   Use Us! Call: 916-726-5675  Or visit our new sales site: 
    www.prestwood.com


    ©1995-2024 Prestwood IT Solutions.   [Security & Privacy]