I have been trying to figure out if there are any differences between these constructors. Assuming there is a Foo() constructor that takes no arguments, are all these constructors going to have the same result?
public Foo()
: this()
{
blah;
blah;
blah;
}
public Foo()
{
this();
blah;
blah;
blah;
}
public Foo()
{
this = new Foo();
blah;
blah;
blah;
}
I would steer clear of assigning to this
in structs. As you can see from the other answers, the very possibility of it is fairly rarely known (I only know because of some weird situation where it turned up in the spec). Where you've got it, it doesn't do any good - and in other places it's likely to be mutating the struct, which is not a good idea. Structs should always be immutable :)
EDIT: Just to make people go "meep!" a little - assigning to this
isn't quite the same as just chaining to another constructor, as you can do it in methods too:
using System;
public struct Foo
{
// Readonly, so must be immutable, right?
public readonly string x;
public Foo(string x)
{
this.x = x;
}
public void EvilEvilEvil()
{
this = new Foo();
}
}
public class Test
{
static void Main()
{
Foo foo = new Foo("Test");
Console.WriteLine(foo.x); // Prints "Test"
foo.EvilEvilEvil();
Console.WriteLine(foo.x); // Prints nothing
}
}
:base()
but not :this()
- gnomed 2013-06-12 18:37
Foo
is a type, so you don't declare the type of that. The original answer was made when there was a parameter called bar
, with no specified type. It's fine to edit the answer because the question was changed, but please only edit it to something meaningful : - Jon Skeet 2013-06-13 07:41
Examples 2 and 3 are not legal C#.
EDIT: Jon points out accurately that 3 is legal when Foo
is a struct
. Go check out his answer!
struct Foo { int a; Foo(Foo other) { this=other; } }
- ja72 2015-04-07 20:10
No they will not because only the first constructor is actually legal. The other two are illegal for various reasons.
EDIT Interesting, 3 is indeed legal when Foo is a struct. But even in that case, it is a redundant assignment.