473,757 Members | 10,736 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Initializing static readonly methods

Hello,
I am new to c# . I have some basic programming doubts. Please help me
in clarifying these doubts.

I want to initialize a static and readonly field with a value returned
by a static method. How ever, when I am debugging, that method is not
being called. So I am not able to figure out, whether the field is
getting initialized properly or not. Please explain this behavior
Thanks in advance

Dec 12 '06 #1
10 7874
Hi Sunil,
at what point are you looking in the debugger? The static field will be
initialized before you try to create an instance of the class or access any
static members or public fields. Do you have a small example where you are
seeing this problem?

Mark
--
http://www.markdawson.org
"sunil" wrote:
Hello,
I am new to c# . I have some basic programming doubts. Please help me
in clarifying these doubts.

I want to initialize a static and readonly field with a value returned
by a static method. How ever, when I am debugging, that method is not
being called. So I am not able to figure out, whether the field is
getting initialized properly or not. Please explain this behavior
Thanks in advance

Dec 12 '06 #2
Static Readonly fields can be only intialized by a static constructor.
You cannot intialize by another static function. Probably thats why you
are having problems in debugging.

Instead you can try using a normal static variable and create a
readonly property for it to exibit the readonly attribute.

-Rahul

sunil wrote:
Hello,
I am new to c# . I have some basic programming doubts. Please help me
in clarifying these doubts.

I want to initialize a static and readonly field with a value returned
by a static method. How ever, when I am debugging, that method is not
being called. So I am not able to figure out, whether the field is
getting initialized properly or not. Please explain this behavior
Thanks in advance
Dec 12 '06 #3

Mark R. Dawson wrote:
Hi Sunil,
at what point are you looking in the debugger? The static field will be
initialized before you try to create an instance of the class or access any
static members or public fields. Do you have a small example where you are
seeing this problem?

Mark
--
http://www.markdawson.org
Hello Mark
Thanks for the quick response. I was looking at the point when a new
object of the class containing the static readonly field is being
instantiated. To give a code example:

class A
{
private static char[] temp = myFunc();
private const i = 9;
private static char[] myFunc()
{
}
internal A
{
}
}

myFunc() returns the char[] at the end.
I was trying to create an object of class A. When the control goes to
the constructor, myFunc() is not being called.

Dec 12 '06 #4
Hi sunil,
the static variable will have been initialized before you enter the
instance constructor. Make sure you set your breakpoint before you begin
execution, then as you step through you will see if working correctly. I
compiled your code and could step into the myFunc method correctly:

using System;

namespace ConsoleApplicat ion1
{
class A
{
private static char[] temp = myFunc();
private const int i = 9;

private static char[] myFunc()
{
return null;
}

internal A()
{
}
}
class Program
{

static void Main(string[] args)
{
A a = new A();
}
}
}

Mark.
--
http://www.markdawson.org
"sunil" wrote:
>
Mark R. Dawson wrote:
Hi Sunil,
at what point are you looking in the debugger? The static field will be
initialized before you try to create an instance of the class or access any
static members or public fields. Do you have a small example where you are
seeing this problem?

Mark
--
http://www.markdawson.org
>
>
Hello Mark
Thanks for the quick response. I was looking at the point when a new
object of the class containing the static readonly field is being
instantiated. To give a code example:

class A
{
private static char[] temp = myFunc();
private const i = 9;
private static char[] myFunc()
{
}
internal A
{
}
}

myFunc() returns the char[] at the end.
I was trying to create an object of class A. When the control goes to
the constructor, myFunc() is not being called.

Dec 12 '06 #5
Hi Rahul,
Static Readonly fields can be only intialized by a static constructor.
You cannot intialize by another static function.
This is not correct, the following is perfectly legal:

using System;
using System.Collecti ons.Generic;
using System.Text;

namespace ConsoleApplicat ion1
{
class Test
{
public static readonly string name = CreateName();

private static string CreateName()
{
return "bob";
}
}

class Program
{

static void Main(string[] args)
{
Test t = new Test();
}
}
}

Mark.
--
http://www.markdawson.org
"Rahul" wrote:
Static Readonly fields can be only intialized by a static constructor.
You cannot intialize by another static function. Probably thats why you
are having problems in debugging.

Instead you can try using a normal static variable and create a
readonly property for it to exibit the readonly attribute.

-Rahul

sunil wrote:
Hello,
I am new to c# . I have some basic programming doubts. Please help me
in clarifying these doubts.

I want to initialize a static and readonly field with a value returned
by a static method. How ever, when I am debugging, that method is not
being called. So I am not able to figure out, whether the field is
getting initialized properly or not. Please explain this behavior
Thanks in advance

Dec 12 '06 #6

Mark R. Dawson wrote:
Hi sunil,
the static variable will have been initialized before you enter the
instance constructor. Make sure you set your breakpoint before you begin
execution, then as you step through you will see if working correctly. I
compiled your code and could step into the myFunc method correctly:

using System;

namespace ConsoleApplicat ion1
{
class A
{
private static char[] temp = myFunc();
private const int i = 9;

private static char[] myFunc()
{
return null;
}

internal A()
{
}
}
class Program
{

static void Main(string[] args)
{
A a = new A();
}
}
}

Mark.
--
http://www.markdawson.org

Hello Mark,
I had tried out that. it works now. Before the private variables gets
instantiated only, the static variables got initialized.
Thanks for clearing my doubts

Dec 12 '06 #7

namespace GroupConsole
{
public class TestClass
{
//This statement will excute even before first instance is
created.
//So assigning a value to readonly is perfectly fine.
public static readonly int data1 = ReturnData();
// public static readonly int data2 = AssignData(); //Error
public static readonly int data2;

private static int ReturnData()
{
return 10;
}

private static void AssignData()
{
data2 = 100; // This can not be done.
// Because method can be called at any point of code.
Changing readonly value is not allowed.
}

static TestClass()
{
data2 = 50; // Perfectly fine.
//readonly values are has to be initialized in constructor.
There is no other place to initialize them.
// because data is static constructor has to be static....
because constructor is static, can not accept arguments.
}
}
class Program
{
static void Main(string[] args)
{
TestClass testobject = new TestClass();
Console.WriteLi ne(TestClass.da ta1.ToString()) ;
Console.WriteLi ne(TestClass.da ta2.ToString()) ;

Console.ReadLin e();
}
}

}
readonly is useful when a constant needs to be initialized by client of
the class. For this the class constructor accepts a parameter and
assigns to readonly. From that point onwards readonly will behave like
a constant.

by qualifyinh a readonly data with static, you can only initialize the
data in a static constructor, which will not accept any parameters.
Meaning that client of the class can not assign the value at the object
initilization. class has to know the value by itself. which is as good
enough as a "const".

Finally.... static readonly data is nothing but const data.

replacing all the static readonly to const will make the code much
readable, because data will be assigned at the point of declaration....
not round a round way....

Hope I am clear what I want to say...

Thanks
-Srinivas.

sunil wrote:
Hello,
I am new to c# . I have some basic programming doubts. Please help me
in clarifying these doubts.

I want to initialize a static and readonly field with a value returned
by a static method. How ever, when I am debugging, that method is not
being called. So I am not able to figure out, whether the field is
getting initialized properly or not. Please explain this behavior
Thanks in advance
Dec 12 '06 #8
Duggi <Du************ ***@gmail.comwr ote:

<snip>
Finally.... static readonly data is nothing but const data.
No. "const" can only be used when the value is known at *compile-time*
(and only for certain types).

For instance, you might have (for whatever reason) a static readonly
field like this:

static readonly DateTime ClassInitializa tionTime = DateTime.Now;

That is constant as far as the process (or rather, AppDomain) is
concerned but it's not a compile-time constant.

Another point about const vs static readonly - if you're going to make
the value public and use it from a class in another assembly, and if
the value may change to a different one in a future version which you
wish to be binary compatible, you should use static readonly: const
values are compiled into "calling" code (i.e. the code reading the
value).

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Dec 12 '06 #9
Thanks a lot mark.. and also at the same point very sorry for my
comment

Mark R. Dawson wrote:
Hi Rahul,
Static Readonly fields can be only intialized by a static constructor.
You cannot intialize by another static function.

This is not correct, the following is perfectly legal:

using System;
using System.Collecti ons.Generic;
using System.Text;

namespace ConsoleApplicat ion1
{
class Test
{
public static readonly string name = CreateName();

private static string CreateName()
{
return "bob";
}
}

class Program
{

static void Main(string[] args)
{
Test t = new Test();
}
}
}

Mark.
--
http://www.markdawson.org
"Rahul" wrote:
Static Readonly fields can be only intialized by a static constructor.
You cannot intialize by another static function. Probably thats why you
are having problems in debugging.

Instead you can try using a normal static variable and create a
readonly property for it to exibit the readonly attribute.

-Rahul

sunil wrote:
Hello,
I am new to c# . I have some basic programming doubts. Please help me
in clarifying these doubts.
>
I want to initialize a static and readonly field with a value returned
by a static method. How ever, when I am debugging, that method is not
being called. So I am not able to figure out, whether the field is
getting initialized properly or not. Please explain this behavior
Thanks in advance
Dec 14 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

33
3351
by: Chris Capel | last post by:
What is the rationale behind the decision not to allow abstract static class members? It doesn't seem like it's a logically contradictory concept, or that the implementation would be difficult or near-impossible. It seems like it would be useful. In fact, there's a place in my code that I could make good use of it. So why not? Chris
22
12048
by: Steve - DND | last post by:
We're currently doing some tests to determine the performance of static vs non-static functions, and we're coming up with some odd(in our opinion) results. We used a very simple setup. One class had a static function, and the one class had a non-static function. Both of these functions did the exact same thing. The test function: public void Test(){ decimal y = 2; decimal x = 3;
3
1751
by: Aaron Watters | last post by:
A C# question about constructors/static methods and inheritance: Please help me make my code simpler! For fun and as an exercise I wrote somewhat classical B-tree implementation in C# which I later ported to java and Python for comparison. http://bplusdotnet.sourceforge.net/ for full details and code ]
19
7716
by: cody | last post by:
Iam wondering what the benefit of using const over static readonly is. static readonly is a runtime constant and can be set once in the initializer or the static ctor, whereas const is suffering from binary incompatibility since it is hardbaked into the binary. I do not believe there is a performance advantage with using const over static readonly since the JIT will take account of that or am I wrong here?
5
2998
by: Sek | last post by:
hi folks, i have a bunch of strings used in my code in many places. these strings reside inside a instantiable class. so, i want to replace these with constant/static variable to control the occurences. i have been looking at both static and const variables as the options, but couldn't decide on one.
8
2772
by: John | last post by:
Hello, is there any compiler option for g++ for initializing static members of the class. Due to some unknown reason, static member in one of our c++ application is not getting initialized properly. Please help me on this. Thanks,
6
2122
by: RichB | last post by:
I am slightly confused regarding when to use an instance method and when to use a static method, particularly in the context of a DAL. I have basically got a class which has methods for CRUD, an object passed into the method an I return an object representing the outcome of the operation or in the casse of a search a Data Transfer Object. Each of my methods are static within an abstract Data Access Class, but I could of course...
3
1844
by: Reckoner | last post by:
would it be possible to use one of an object's methods without initializing the object? In other words, if I have: class Test: def __init__(self): print 'init' def foo(self): print 'foo'
5
1736
by: pgrazaitis | last post by:
I cant seem to get my head wrapped around this issue, I have myself so twisted now there maybe no issue! Ok so I designed a class X that has a few members, and for arguments sake one of the members Y is the location of a file to be read. The original design assumes that this class will be instantiated and each instance will happily mange its own members. (ie One file location per instance...no thread-safety). Now another class A...
0
9298
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10072
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9906
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9737
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7286
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6562
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3829
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3399
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2698
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.