473,382 Members | 1,404 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 software developers and data experts.

anonymous initializer problem

Hi,

I need to initialize my class level dictionary (in .Net 2.0). I wanted to
make it inline and employ anonymous methods as I do not use this code for
anything else. Something similar to the following:

private static Dictionary<string, field_fields = delegate()
{
Dictionary<string, fieldresult = new Dictionary<string, field>();
result.Add("Application", new field("Application", "AppName"));
...
return result;
};

And then I need to use the dictionary values in the rest of the declarations.

Apparently the code above does not compile with the error: "Cannot convert
anonymous method block to type
'System.Collections.Generic.Dictionary<string,Grou pDates.field>' because it
is not a delegate type".

I understand that it is not - but what is the correct way to initialize a
variable with anonymous method (and is there)?
I could always create a method that would return the correct initialized
object, but would prefer not to.

Any suggestions are appreciated.

Jun 5 '07 #1
12 2683

"Sergey Poberezovskiy" <Se*****************@discussions.microsoft.comwrot e
in message news:4B**********************************@microsof t.com...
Hi,

I need to initialize my class level dictionary (in .Net 2.0). I wanted to
make it inline and employ anonymous methods as I do not use this code for
anything else. Something similar to the following:

private static Dictionary<string, field_fields = delegate()
{
Dictionary<string, fieldresult = new Dictionary<string, field>();
result.Add("Application", new field("Application", "AppName"));
...
return result;
};

And then I need to use the dictionary values in the rest of the
declarations.

Apparently the code above does not compile with the error: "Cannot convert
anonymous method block to type
'System.Collections.Generic.Dictionary<string,Grou pDates.field>' because
it
is not a delegate type".

I understand that it is not - but what is the correct way to initialize a
variable with anonymous method (and is there)?
I could always create a method that would return the correct initialized
object, but would prefer not to.
The C# compiler just puts the initializer code in the static constructor, so
that's what you should do too.

private static readonly Dictionary<string, field_fields;

static ClassName()
{
_fields = new Dictionary<string, field>();
_fields.Add("Application", new field("Application", "AppName"));
}

>
Any suggestions are appreciated.

Jun 5 '07 #2
Ben,

Compiler does not allow putting executable code in the declaration section -
all such code needs to be inside methods/properties :-(

"Ben Voigt [C++ MVP]" wrote:
>
"Sergey Poberezovskiy" <Se*****************@discussions.microsoft.comwrot e
in message news:4B**********************************@microsof t.com...
Hi,

I need to initialize my class level dictionary (in .Net 2.0). I wanted to
make it inline and employ anonymous methods as I do not use this code for
anything else. Something similar to the following:

private static Dictionary<string, field_fields = delegate()
{
Dictionary<string, fieldresult = new Dictionary<string, field>();
result.Add("Application", new field("Application", "AppName"));
...
return result;
};

And then I need to use the dictionary values in the rest of the
declarations.

Apparently the code above does not compile with the error: "Cannot convert
anonymous method block to type
'System.Collections.Generic.Dictionary<string,Grou pDates.field>' because
it
is not a delegate type".

I understand that it is not - but what is the correct way to initialize a
variable with anonymous method (and is there)?
I could always create a method that would return the correct initialized
object, but would prefer not to.

The C# compiler just puts the initializer code in the static constructor, so
that's what you should do too.

private static readonly Dictionary<string, field_fields;

static ClassName()
{
_fields = new Dictionary<string, field>();
_fields.Add("Application", new field("Application", "AppName"));
}


Any suggestions are appreciated.


Jun 5 '07 #3
Ben,

disregards my previos message - I should have read more carefully - my bad.

Though this is a way to initialize - I wanted to accomplish the
initialization inside the declaration section (before it gets to the static
constructor). The reason for that is that the next lines inside the
costructor declare custom static arrays that use the dictionary values, such
as
private static readonly field[] _REQUIRED_COLUMNS = {_fields["Name1"], ...};
....
private static readonly field[] _CUSTOM_COLUMNS = {_fields["NameN"], ...};

Originally I had just the arrays declarations, and then I noticed that at
times a field name was changed in one array, but not in ALL. As a solution I
created a dictionary to hold the values, so that the change needs to happen
in one place only.

Hope it makes sense
"Ben Voigt [C++ MVP]" wrote:
>
"Sergey Poberezovskiy" <Se*****************@discussions.microsoft.comwrot e
in message news:4B**********************************@microsof t.com...
Hi,

I need to initialize my class level dictionary (in .Net 2.0). I wanted to
make it inline and employ anonymous methods as I do not use this code for
anything else. Something similar to the following:

private static Dictionary<string, field_fields = delegate()
{
Dictionary<string, fieldresult = new Dictionary<string, field>();
result.Add("Application", new field("Application", "AppName"));
...
return result;
};

And then I need to use the dictionary values in the rest of the
declarations.

Apparently the code above does not compile with the error: "Cannot convert
anonymous method block to type
'System.Collections.Generic.Dictionary<string,Grou pDates.field>' because
it
is not a delegate type".

I understand that it is not - but what is the correct way to initialize a
variable with anonymous method (and is there)?
I could always create a method that would return the correct initialized
object, but would prefer not to.

The C# compiler just puts the initializer code in the static constructor, so
that's what you should do too.

private static readonly Dictionary<string, field_fields;

static ClassName()
{
_fields = new Dictionary<string, field>();
_fields.Add("Application", new field("Application", "AppName"));
}


Any suggestions are appreciated.


Jun 5 '07 #4

"Sergey Poberezovskiy" <Se*****************@discussions.microsoft.comwrot e
in message news:B0**********************************@microsof t.com...
Ben,

disregards my previos message - I should have read more carefully - my
bad.

Though this is a way to initialize - I wanted to accomplish the
initialization inside the declaration section (before it gets to the
static
constructor). The reason for that is that the next lines inside the
costructor declare custom static arrays that use the dictionary values,
such
as
private static readonly field[] _REQUIRED_COLUMNS = {_fields["Name1"],
...};
...
private static readonly field[] _CUSTOM_COLUMNS = {_fields["NameN"], ...};

Originally I had just the arrays declarations, and then I noticed that at
times a field name was changed in one array, but not in ALL. As a solution
I
created a dictionary to hold the values, so that the change needs to
happen
in one place only.

Hope it makes sense
If you want to control the order of initialization, you need to put it all
in the static constructor.

Also, I hope that you realize that your readonly arrays are fixed in size,
but not in content. If you need fixed content you should go for something
like ReadonlyCollection.
>

"Ben Voigt [C++ MVP]" wrote:
>>
"Sergey Poberezovskiy" <Se*****************@discussions.microsoft.com>
wrote
in message news:4B**********************************@microsof t.com...
Hi,

I need to initialize my class level dictionary (in .Net 2.0). I wanted
to
make it inline and employ anonymous methods as I do not use this code
for
anything else. Something similar to the following:

private static Dictionary<string, field_fields = delegate()
{
Dictionary<string, fieldresult = new Dictionary<string, field>();
result.Add("Application", new field("Application", "AppName"));
...
return result;
};

And then I need to use the dictionary values in the rest of the
declarations.

Apparently the code above does not compile with the error: "Cannot
convert
anonymous method block to type
'System.Collections.Generic.Dictionary<string,Grou pDates.field>'
because
it
is not a delegate type".

I understand that it is not - but what is the correct way to initialize
a
variable with anonymous method (and is there)?
I could always create a method that would return the correct
initialized
object, but would prefer not to.

The C# compiler just puts the initializer code in the static constructor,
so
that's what you should do too.

private static readonly Dictionary<string, field_fields;

static ClassName()
{
_fields = new Dictionary<string, field>();
_fields.Add("Application", new field("Application", "AppName"));
}

>
Any suggestions are appreciated.



Jun 5 '07 #5
On Jun 5, 2:39 pm, "Ben Voigt [C++ MVP]" <r...@nospam.nospamwrote:

<snip>
If you want to control the order of initialization, you need to put it all
in the static constructor.
That's not strictly true - the spec states that static variable
initializers are executed in the textual order in which they appear in
the class declaration, and all of them are run before the static
constructor. When you've got partial classes, the ordering is less
well defined, admittedly.

I'd say that as a matter of readability and making the system vaguely
robust, I wouldn't want to rely on the order (because someone may
inadvertently change it) but it *should* work according to the spec.

Jon

Jun 5 '07 #6

"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:11*********************@q66g2000hsg.googlegro ups.com...
On Jun 5, 2:39 pm, "Ben Voigt [C++ MVP]" <r...@nospam.nospamwrote:

<snip>
>If you want to control the order of initialization, you need to put it
all
in the static constructor.

That's not strictly true - the spec states that static variable
initializers are executed in the textual order in which they appear in
the class declaration, and all of them are run before the static
constructor. When you've got partial classes, the ordering is less
well defined, admittedly.

I'd say that as a matter of readability and making the system vaguely
robust, I wouldn't want to rely on the order (because someone may
inadvertently change it) but it *should* work according to the spec.

I was considering that behavior "too brittle for words", but I now see I am
wrong. There are words...
Jon

Jun 5 '07 #7
On Jun 5, 4:05 pm, "Ben Voigt [C++ MVP]" <r...@nospam.nospamwrote:
I'd say that as a matter of readability and making the system vaguely
robust, I wouldn't want to rely on the order (because someone may
inadvertently change it) but it *should* work according to the spec.

I was considering that behavior "too brittle for words", but I now see I am
wrong. There are words...
Oh I certainly wasn't recommending doing it. Just pointing out the
difference between "never ever do this" and "it's not guaranteed to
work". It's guaranteed to work so long as no-one ever touches the code
again :)

Jon

Jun 5 '07 #8

"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:11**********************@h2g2000hsg.googlegro ups.com...
On Jun 5, 4:05 pm, "Ben Voigt [C++ MVP]" <r...@nospam.nospamwrote:
I'd say that as a matter of readability and making the system vaguely
robust, I wouldn't want to rely on the order (because someone may
inadvertently change it) but it *should* work according to the spec.

I was considering that behavior "too brittle for words", but I now see I
am
wrong. There are words...

Oh I certainly wasn't recommending doing it. Just pointing out the
difference between "never ever do this" and "it's not guaranteed to
work". It's guaranteed to work so long as no-one ever touches the code
again :)
One might as well check the compiled binary into version control and throw
away the code... less tempting to break it that way.
>
Jon

Jun 5 '07 #9
Ben Voigt [C++ MVP] <rb*@nospam.nospamwrote:
Oh I certainly wasn't recommending doing it. Just pointing out the
difference between "never ever do this" and "it's not guaranteed to
work". It's guaranteed to work so long as no-one ever touches the code
again :)

One might as well check the compiled binary into version control and throw
away the code... less tempting to break it that way.
Nearly. On the other hand, it's not exactly infeasible to put big
comments warning what's going on and why. I know I've had brittle code
for "good reason" before now. On the other hand, in this case using a
static constructor is a better way to proceed (unless the slight
performance hit of having a static constructor over just static
initializers is significant, which would be remarkable in itself).

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jun 5 '07 #10
Ben,

I do realize that - I use arrays here just so that it is clearly defined in
the declaration section (via initializer). It is just the way I structure my
classes - constants and readonly fields first, then other declarations,
constructors, etc.
This way it is always clear where to go to see/change those definitions -
and that was the reason why I did not want that to be in either constructor
or a static method (which would also work).

At the end I just defined a private class that inherits the typed dictionary
and has only one public constructor that takes an array of field objects.
This way I could define my dictionary in the declaration section where it is
clearly seen:

private class fields : Dictionary<string, field>
{
public fields(field[] array)
{
foreach (field item in array)
{
this.Add(item.Key, item);
}
}
}

private static readonly fields _fields = new fields(
new field[] {
new field("Application", "AppName"),
...
}
);

It is not "anonymous", but is clearly defined in the declaration section -
as I wanted.

Thank you both for your time.

"Ben Voigt [C++ MVP]" wrote:
>
"Sergey Poberezovskiy" <Se*****************@discussions.microsoft.comwrot e
in message news:B0**********************************@microsof t.com...
Ben,

disregards my previos message - I should have read more carefully - my
bad.

Though this is a way to initialize - I wanted to accomplish the
initialization inside the declaration section (before it gets to the
static
constructor). The reason for that is that the next lines inside the
costructor declare custom static arrays that use the dictionary values,
such
as
private static readonly field[] _REQUIRED_COLUMNS = {_fields["Name1"],
...};
...
private static readonly field[] _CUSTOM_COLUMNS = {_fields["NameN"], ...};

Originally I had just the arrays declarations, and then I noticed that at
times a field name was changed in one array, but not in ALL. As a solution
I
created a dictionary to hold the values, so that the change needs to
happen
in one place only.

Hope it makes sense

If you want to control the order of initialization, you need to put it all
in the static constructor.

Also, I hope that you realize that your readonly arrays are fixed in size,
but not in content. If you need fixed content you should go for something
like ReadonlyCollection.


"Ben Voigt [C++ MVP]" wrote:
>
"Sergey Poberezovskiy" <Se*****************@discussions.microsoft.com>
wrote
in message news:4B**********************************@microsof t.com...
Hi,

I need to initialize my class level dictionary (in .Net 2.0). I wanted
to
make it inline and employ anonymous methods as I do not use this code
for
anything else. Something similar to the following:

private static Dictionary<string, field_fields = delegate()
{
Dictionary<string, fieldresult = new Dictionary<string, field>();
result.Add("Application", new field("Application", "AppName"));
...
return result;
};

And then I need to use the dictionary values in the rest of the
declarations.

Apparently the code above does not compile with the error: "Cannot
convert
anonymous method block to type
'System.Collections.Generic.Dictionary<string,Grou pDates.field>'
because
it
is not a delegate type".

I understand that it is not - but what is the correct way to initialize
a
variable with anonymous method (and is there)?
I could always create a method that would return the correct
initialized
object, but would prefer not to.

The C# compiler just puts the initializer code in the static constructor,
so
that's what you should do too.

private static readonly Dictionary<string, field_fields;

static ClassName()
{
_fields = new Dictionary<string, field>();
_fields.Add("Application", new field("Application", "AppName"));
}

Any suggestions are appreciated.



Jun 6 '07 #11
Jon Skeet [C# MVP] wrote:
On Jun 5, 4:05 pm, "Ben Voigt [C++ MVP]" <r...@nospam.nospamwrote:
>>I'd say that as a matter of readability and making the system vaguely
robust, I wouldn't want to rely on the order (because someone may
inadvertently change it) but it *should* work according to the spec.
I was considering that behavior "too brittle for words", but I now see I am
wrong. There are words...

Oh I certainly wasn't recommending doing it. Just pointing out the
difference between "never ever do this" and "it's not guaranteed to
work". It's guaranteed to work so long as no-one ever touches the code
again :)
In general it is not wise to assume that everybody that will have
to maintain the code for the next 10-20 year have memorized the
language specs.

KISS is one of the most important rules.

Arne
Jun 7 '07 #12
Arne Vajhøj <ar**@vajhoej.dkwrote:
Oh I certainly wasn't recommending doing it. Just pointing out the
difference between "never ever do this" and "it's not guaranteed to
work". It's guaranteed to work so long as no-one ever touches the code
again :)
In general it is not wise to assume that everybody that will have
to maintain the code for the next 10-20 year have memorized the
language specs.

KISS is one of the most important rules.
Absolutely - can't (and wouldn't) argue with that. I think we're all in
violent agreement there.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jun 7 '07 #13

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

Similar topics

3
by: H. S. | last post by:
Hi, I am trying to compile these set of C++ files and trying out class inheritence and function pointers. Can anybody shed some light why my compiler is not compiling them and where I am going...
2
by: Todd Nathan | last post by:
Hi. have this code and compiler problem. GCC 2.95.3, BeOS, error "initializer element is not constant" #ifdef FILEIO { static struct { char *sfn; FILE *sfd; } stdfiles = {
6
by: Marty M | last post by:
The following causes the "invalid initializer" message during gcc compile time... char firstword = word(question,1); the "word" function is... char * word(char *phrase, int what) {...body...
1
by: qwerty2_reverse_iterator | last post by:
Is this a bug with the ms compiler (V7.1)? (It seems so at least.) I get errors when I don't initialize all the const pointer fields of an anonymous union in a struct. Example: //T2.h...
3
by: Levi Campbell | last post by:
Hi, I'm trying to debug an app someone else wrote called eMixer. Here's the log contents: cc -O3 -funroll-loops -c -o main.o main.c cc -O3 -funroll-loops -c -o nctgui.o nctgui.c cc -O3...
6
by: Marvin Barley | last post by:
I have a class that throws exceptions in new initializer, and a static array of objects of this type. When something is wrong in initialization, CGI program crashes miserably. Debugging shows...
60
by: jacob navia | last post by:
Gnu C features some interesting extensions, among others compound statements that return a value. For instance: ({ int y = foo(); int z; if (y>0) z = y; else z=-y; z; }) A block enclosed by...
2
by: anon.asdf | last post by:
Hello! 1) =============================== When trying to define an array of std::string ... func( (std::string ) { std::string("ab"), std::string("cd"), std::string("ef") } , 3 ); ...
9
by: andreyvul | last post by:
I'm trying to do the following: typedef struct { char *bar; char **baz; } foo; const foo fop = { { "foo", { "bar", "baz", "bax" } }, { "goo", { "car", "cdr", "cfr" } }
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.