Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Assigning constructor values in object arrays 1

Status
Not open for further replies.

BobRodes

Instructor
May 28, 2003
4,215
0
0
US
I have a class that assigns a string property in the constructor, thus:
Code:
public class Test
{
    public string StrProp {get; set;}
    public Test(string myString)
    {
        StrProp = myString;
    }
}

I'm attempting to create an array of this class. I first attempted it this way:
Code:
Test[] myTests = new Test[7]; { "Anne", "Bob", "John" };
but the compiler thinks I'm trying to cast the strings as object references. I find that this works fine:
Code:
Test[] myTests = new Test[7]; 
myTests[0] = new Test("Anne");
myTests[1] = new Test("Bob");
myTests[2] = new Test("John");
but it's tedious and inelegant. Is there a cleaner way to do this?

TIA
 
Code:
var array = new []
{
   new Test("Anne"),
   new Test("Bob"),
   new Test("John"),
};

Jason Meckley
Programmer

faq855-7190
faq732-7259
 
Ok, so I tried this:
Code:
            var myTests = new []
            {
                new Test("Anne"),
                new Test("Bob"),
                new Test("John"),
            };
            Console.WriteLine(myTests.GetType());
The console did indeed show TestLib.Test[], suggesting that the type is resolved at compile time. This is a thing of beauty for a VB6 programmer who did his best to avoid Variant variables. Thanks Jason!
 
var isn't a variant, it's syntax sugar for the explicit type. for example, this will not compile
Code:
var array = new [] {"1", 1, new Test("me")};
but this will
Code:
var array = new object [] {"1", 1, new Test("me")};
when this code is compiled into an assembly it will result in
Code:
object[] array = new object[3];
array[0] = "1";
array[1] = 1;
array[2] = new Test("me");
the var keyword reduces the repetitive nature of the strongly typed language.

the [tt]dynamic[/tt] keyword was introduced in .net 4.0 which allows the strongly typed language to behave like a dynamic language. this is more along the lines of a variant object.
Code:
dynamic foo = new {};
foo.Bar = 1;
foo.Baz = "a";
string.Format("{0}[{1}, {2}]", foo, foo.Bar, foo.Baz);

Jason Meckley
Programmer

faq855-7190
faq732-7259
 
Ok, your second example is compiling because each of the given values can be cast as an object? And that said, is it equivalent to
Code:
object array = new object [] {"1", 1, new Test("me")};
?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top