Syntax for property parameters?

  • Thread starter Thread starter Kel Good
  • Start date Start date
K

Kel Good

Hi,

I'm learning C# after having learned VB.Net, so I am trying to get a grip on
syntax differenced. In VB.Net I can define a parameterized property like so:

Public Property MyProperty(ByVal myValue As String) As String
Get

End Get
Set

End Set
End Property

I've tried to do the same in C#, but it doesn't seem to want me to:

public String MyProperty (String myValue)
{
get{}
set{}
}

What am I doing wrong?

Thanks.

Kel
 
Hi Kel,

This is how you can write properties in c#

class myclass
{
String myprop;
public String MyProperty ()
{
get
{
return myprop;
}
set
{
myprop = value;

}
}
}

In the set block above, value of the variable "value" will be what you
pass to it

myclass m = new myclass();
m.MyProperty = "Kel"; // the value of variable "value" will be Kel,
which will then be assigned to its priv. variable as you can see above

Did this clear your question ?

Kalpesh
 
Hi Kel,

This is how you can write properties in c#

class myclass
{
String myprop;
public String MyProperty ()
{
get
{
return myprop;
}
set
{
myprop = value;

}
}
}

In the set block above, value of the variable "value" will be what you
pass to it

myclass m = new myclass();
m.MyProperty = "Kel"; // the value of variable "value" will be Kel,
which will then be assigned to its priv. variable as you can see above

Did this clear your question ?

Kalpesh
 
Note that in C# properties cannot take parameters, so on the example above,
you need to remove the parenthesis:

string myprop;
public string MyProperty
{
get
{
return myprop;
}
set
{
myprop = value;
}
}

if you need to send parameters you can consider using indexers:

class MyClass
{
string myprop;
public string this [int param1, int param2]
{
get
{
return myprop;
}
set
{
myprop = value;
}
}
}

you can use the indexe in this way:
void method()
{
MyClass mc = new MyClass();
mc[1, 2] = "hello";
}
 
Back
Top