0

If I have a class like below, how would I create the function nullToEmptyString()?
If object is DBNull.Value then return an empty string, otherwise return the value. The function should work on every object in person.

public class Person
{
    public object surname { get; set; }
    public object lastname { get; set; }
    public object zip_code { get; set; }
    public object tele { get; set; }
}  

I retrieve a list of persons from the DB and I want to print the value, if it has a value, otherwise an empty string.

foreach (var person in listFromDB)
{
    person.surname.nullToEmptyString()
    person.lastname.nullToEmptyString()
}  

EDIT
In short, this function should work like the .ToString() function but would also be able to handle DBNull values.

3
  • A string is immutable, so you cannot change the current instance. You'll have to use a syntax like: person.surname = person.surname.nullToEmptyString(); Commented Jun 9, 2011 at 9:02
  • So the two answers here are invalid? Commented Jun 9, 2011 at 9:06
  • Nopes. They both are valid. it depends whether you wish to modify the person class values or you want to display. If you wish to modify, you need to do as suggested by @Arjen, or else I have just displayed the values which can even be taken in separate variables. Commented Jun 9, 2011 at 9:20

2 Answers 2

1
public static string nullToEmptyString(this string dbStr)
{
    return (dbStr == null || dbStr == "") ? "" : dbStr;
}

foreach (var person in listFromDB)
{
    Response.Write(person.surname.nullToEmptyString());
    Response.Write(person.lastname.nullToEmptyString());
}

Hope this helps.

Sign up to request clarification or add additional context in comments.

5 Comments

ah, so this points to the object you run .nullToEmptyString() on?
Yes. This is a new fundamental kin C# 3.0 called as extension methods.
Where should I create this function? I get the error Extension method must be defined in a non-generic static class if I try to make it a function in my Person class.
Ah yes. Forgot. You can create a new static class and define the above method as static.
Yep, works like a charm =). I only need it for print and not to actually change the type.
1

Try something like

public string Somename(this string somestring)
{
      return somestring ?? "";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.