Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

6
  • Thanks, It works, but can you compare your answer with others(Rune Grimstad,Fredrik Mörk ) I am confused now which one is best practice Commented Jan 4, 2010 at 12:04
  • 1
    If you only want to get 1 value, ExecuteScalar is a good method to use. You just have to be careful how you handle the object you get. Using the as-operator will not throw a NullReferenceException when casting null to a string. Commented Jan 4, 2010 at 12:08
  • 1
    The: object o = null; string s = (string)o; does not throw an exception, so I'm wondering if the exception was really because of ExecuteScalar() returning a null? @HemantKothiyal did you actually test this in run-time and confirmed that replacing a cast with as stops the exception? And did you get the expected result in getusername? Commented Oct 31, 2011 at 0:37
  • 1
    @HemantKothiyal BTW, string getusername = command.ExecuteScalar(); does not compile - error CS0266: Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?) Could you post the actual code you have used? Commented Oct 31, 2011 at 0:53
  • @HemantKothiyal check the msdn about "as" operator ( msdn.microsoft.com/zh-tw/library/cscsdfbt.aspx ) The as operator is like a cast operation.However, if the conversion isn't possible, as returns null instead of raising an exception.Consider the following example: Commented Feb 16, 2016 at 6:44