Adding validation in Property

R

RP

I am using following code to validate the value that is being assigned
via property. But it is not working:

----------------------------------------
public string vProductName
{
get
{
return ProductName;
}
set
{
ProductName = value;
if (ProductName == null)
{ ProductName = "-"; }
}
}
 
M

Marc Gravell

Can you illustrate with an example? Perhaps the ProductName property
is doing something interesting...

For info, another option here would be the null-coalescing operator:
set {
ProductName = value ?? "-";
}

Marc
 
K

KWienhold

You may refer my post in this forum:http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2362415&SiteID=1

While initializing values in a property, I want to check whether it is
a null. If yes, then I want the value to be "-".

----------------------------------------------------------



- Zitierten Text anzeigen -

The code looks feasible, it should work (although Marc's suggestion of
using ?? is more elegant imho).
Looking at the code you posted in the MSDN forums you should be aware
of one thing though:
If someone calls the constructor with "null" as "_ProductName", your
property "vProductName" will return null, since the set-part of the
property is never called in this case.
You should set the property in the constructor (vProductName =
_ProductName) if you want your input to be validated, not the field.
Depending on the situation this may be the cause of the problem you
are seeing, unfortunately the conditions of your test aren't clear in
your post.

hth,
Kevin Wienhold
 
K

KWienhold

You may refer my post in this forum:http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2362415&SiteID=1

While initializing values in a property, I want to check whether it is
a null. If yes, then I want the value to be "-".

----------------------------------------------------------



- Zitierten Text anzeigen -

Forgot to mention:
A similar problem will crop up if you call the parameterless
constructor, since "ProductName" will remain at its initial value.
Since String is a reference type, its initial value is "null".

hth,
Kevin Wienhold
 

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

Top