Hi ,
Can i populate the class variables in following fashion?
public class abc
{
string name;
public string Name
{
set
{
name = value;
}
}
public abc()
{
}
}
abc myclass1 = new abc()
abc.Name="google";
or
should I always populate through constructor or any other method of
class abc?
thanks
Vijay
Jon Skeet [C# MVP] - 28 May 2008 16:31 GMT
> Can i populate the class variables in following fashion?
<snip>
Absolutely - that's what most writable properties look like.
> or
>
> should I always populate through constructor or any other method of
> class abc?
Well, if you want to create an immutable type you need to pass
everything to the constructor, but if you're okay with mutability,
there's nothing wrong with using a writable property.
Jon
vijaysambhe - 28 May 2008 16:51 GMT
Thanks Jon for your prompt reply.
regards
Vijay
> > Can i populate the class variables in following fashion?
>
[quoted text clipped - 12 lines]
>
> Jon
Family Tree Mike - 28 May 2008 17:52 GMT
I think you made a typo below. It should be:
abc myclass1 = new abc();
myclass1.Name="google"; // apc.Name will not be correct...
> Hi ,
>
[quoted text clipped - 27 lines]
>
> Vijay
Ignacio Machin ( .NET/ C# MVP ) - 28 May 2008 22:09 GMT
> Can i populate the class variables in following fashion?
Of course, there is nothing wrong with that
> or
>
> should I always populate through constructor or any other method of
> class abc?
It depends of the class, if the class needs to ALWAYS have a value for
a given property then you use yor constructor for that.
Also providing a constructor with parameters let you do something
like:
callAMethod( new MyClass( ......) );
without having to create an instance of MyClass (note that in 3.5 this
is no longer valid).
BTW, to a class like yours it's usually called to have a "chatty
interface"