property in a class

  • Thread starter Thread starter vijaysambhe
  • Start date Start date
V

vijaysambhe

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
 
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
 
Thanks Jon for your prompt reply.

regards
Vijay
<snip>

Absolutely - that's what most writable properties look like.



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
 
I think you made a typo below. It should be:

abc myclass1 = new abc();
myclass1.Name="google"; // apc.Name will not be correct...
 
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"
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top