Re: Variable declaration/definition
- From: Jon Skeet [C# MVP] <skeet@xxxxxxxxx>
- Date: Thu, 26 Jun 2008 20:19:18 +0100
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
.
- Follow-Ups:
- Re: Variable declaration/definition
- From: Annonymous Coward
- Re: Variable declaration/definition
- From: Jon Skeet [C# MVP]
- Re: Variable declaration/definition
- References:
- Variable declaration/definition
- From: Annonymous Coward
- Variable declaration/definition
- Prev by Date: Re: A surprising fix for column ordering of a dynamic DataGridView
- Next by Date: Re: sincronizing two combo boxes
- Previous by thread: Re: Variable declaration/definition
- Next by thread: Re: Variable declaration/definition
- Index(es):
Relevant Pages
|