Jesper Nielsen
Jesper Nielsen

Reputation: 41

c# string.length

This simple code:

    [HttpPost]
    public ActionResult Check(string chosen_username, string email) {
        var lang = RouteData.Values["lang"]; ViewBag.Language = lang;

        string un; string em;
        try {
            un = chosen_username; em = email;
        }
        catch { un = ""; em = ""; }

        string s = un.Length.ToString();
        ViewBag.test = s;

        return View();
    }

Throws the object reference not set to an instance of an object-exception (on the line that reads "string s = un.Length.ToString();"

Could anybody help a C# newbie out please?

Upvotes: 2

Views: 40278

Answers (3)

Ismail Hawayel
Ismail Hawayel

Reputation: 2453

you should get that null pointer exception if chosen_username is null, since you never initialized your un string variable,

you should either: - check for null input - initialize your function local variables - assign them to avoid null as in : un = chosen_username ?? string.Empty;

Upvotes: 0

Marco
Marco

Reputation: 57593

I think you did not initialize ViewBag object or it is null.
Try this

if (ViewBag != null)
    ViewBag.test = un.Length.ToString();

To be sure that problem is not in string (and it's not, believe me) try this

string s = un.Length.ToString();

and use debugger to check that s is the one you expected.

EDITED after OP posted new code:
Simply: string un is null!! Try using

if (!String.IsNullOrEmpty(un))
    ViewBag.test = un.Length.ToString();
else {
    // Manage here the error
}

Upvotes: 5

Curtis
Curtis

Reputation: 103428

Object reference exception is referring to your ViewBag object, not your un.Length.ToString() value.

The following should run fine:

string un = "test"; string em = "test";
string test = un.Length.ToString();

Upvotes: 0

Related Questions