Re: Variable declaration/definition



Annonymous Coward <me@xxxxxxxx> wrote:
I am relatively new in C#, but have several years C++/Java. I am writing
a little C# console app to "test the waters" and learn the language.

If I have a class defined as:

class MyClass
{
MyClass(string s1, int i2, bool b3)
{
}
}


Why can't I declare a variable on the stack somewhere later on in my
code like this:

// .... code above
MyClass mc("Hello",42, true);

That's not how you invoke a constructor in C#. You can just declare a
variable, of course:

MyClass mc;

but that won't create an instance.

Do I always have to alloc from the heap when instantiating objects whose
ctor have parameters?

You always have to allocate from the heap whenever you create *any*
objects, regardless of whether there are parameterless constructors. In
that respect C# is identical to Java. Basically C# is closer to Java
than it is to C++ in many ways.

Note, however, that "new" doesn't always mean "allocate from the heap".
For instance, consider:

DateTime dt = new DateTime(2008, 06, 26);

That calls the DateTime constructor, but doesn't allocate anything on
the heap (assuming it's a normal local variable), because DateTime is a
value type. In this respect C# is different to Java, as Java doesn't
have custom value types, just the primitives.

--
Jon Skeet - <skeet@xxxxxxxxx>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon_skeet
C# in Depth: http://csharpindepth.com
.



Relevant Pages

  • Re: Is it good programming to set instance in class without using C-tor
    ... I have a class definition called MyClass see below. ... I create an instance of this class MyClass ... the question of what arguments should go on the constructor is ... your client has to test before they try to use an object instance. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Variable declaration/definition
    ... class MyClass ... MyClass mc; ... Basically C# is closer to Java than it is to C++ in many ways. ... That calls the DateTime constructor, but doesn't allocate anything on the heap, because DateTime is a value type. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: noobie: copy data in a constructor
    ... > Class MyClass { ... > public MyClass() { ... > constructor because you can't assign the variable 'this' ... a factory method. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: can I declare a class variable inside that class method?
    ... > class MyClass{ ... Because the copy constructor parameter is passed by value, ... the MyClass copy constructor would have to be invoked. ...
    (comp.lang.cpp)
  • Re: Object creation overhead
    ... > class MyClass ... This is, of course, over and above the memory required for the ... > 'MyClass' objects themselves. ... > The 'proxy' class approach won't see a reduction in the number of ...
    (comp.lang.java)