Default Property Value in C#

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have created a static class which contains properties. I can assign values
to them when the software is running. How can I create default values for
these properties when I am coding them, so that I can retrieve those values
without assigning a new one when the software is running?
 
Belee,

If the values are primitive types, you can just declare the value in the
declaration of the static field.

If you require some more intricate initialization, then you can define a
static constructor, like this:

static()
{
// Do static initialization here.
}

Hope this helps.
 
either by assigning default value to variable in declaration
class MyClass {

public static string Variable1 = "Value1";

}

or assigning a value in static constructor

class MyClass{

public static string Variable1;

public static MyClass(){

Variable1 = "Value1";

}

}


Mihir Solanki
http://www.mihirsolanki.com
 
Hi Belee,

I see that Nicholas and Mihir gave you already the solution I just want to
clear one point. If you look at the docs you may see an attribute called
DefaultValue. This attribute can be applied to properties, but it doesn't
provide the initial value for the attribute. It is merely used in the
property browser and visual designers, but it deosn't intialize the
property.

Constructor (instance or static) or the *get* accessor for the property is
the plaease where the initial value should be givien.
 
private string _myThing = "default property";
public string MyThing
{
get{ return _myThing;}
set{ _myThing = value;}
}

Cheers.
Peter
 
Nicholas Paldino said:
If the values are primitive types, you can just declare the value in the
declaration of the static field.

If you require some more intricate initialization, then you can define a
static constructor, like this:

static()
{
// Do static initialization here.
}

Even if you require more intricate construction, you can call methods:

using System;
using System.Collections;

public class Test
{
static Hashtable map = CreateMap();

static void Main()
{
Console.WriteLine (map["first"]);
}

static Hashtable CreateMap()
{
Hashtable ret = new Hashtable();
ret["first"] = "hi";
ret["second"] = "there";
return ret;
}
}

Static constructors have a small performance penalty for frequent uses
of static methods (due to the lack of a beforefieldinit flag).

Strangely enough though, I tend to use static constructors despite
(just now) finding the above a neater way of doing things. Hmm.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top