Is there a null handler to string method at c# - c#

I am able to assign a variable like below:
if (Session["myVariable"] != null)
{
string variAble = Session["myVariable"].ToString();
}
Is there a method which checks whether an object is null or not and then assign if it is not null?

string variAble = Session["myVariable"] ?? "";
EDIT A slightly more robust form, as suggested by #hatchet, is:
string variAble = (Session["myVariable"] ?? "").ToString();

While this isn't anything new, you can use the conditional operator to potentially simplify this:
string variable = Session["myVariable"] != null ? Session["myVariable"].ToString() : "Fallback";

You could write an extension method, as those still work with null objects.
public static class StringExtensions
{
public static String ToNullString(this object o)
{
return o == null ? "" : o.ToString();
}
}
I would consider it poor form though - it'll be confusing to whoever will be supporting the code after you, or even to you a few months down the track. It's probably better to just do the null check.

Related

How to set default values to string if it is null or empty

Is there Better way to check if a string is empty or null using Null Coalescing operator .When I use empty value to a string instead of null the null Coalescing operator failed to get me the desired result.
string x = null;
string y = x ?? "Default Value";
Console.WriteLine(y);
Here if I replace x = null with x="" this doesnt work.
If I use String.IsNullOrEmpty method
if(String.IsNullOrEmpty(x)
{
y= "default value"
}
{
y =x
}
My code block is having multiple lines and I want to make it simple. Can you suggest a better way to keep the code clean and simple. As it is used in many places.
You can use the ? operator
string x = null;
string y = string.IsNullOrEmpty(x) ? "Default Value" : x;
Console.WriteLine(y);
Given that you say "it is used in many places" then it might be appropriate to write an extension method to help with this:
public static class StringExt
{
public static string OrIfEmpty(this string? self, string defaultValue)
{
return !string.IsNullOrEmpty(self) ? self : defaultValue;
}
}
Which you would use like so:
string? x = null;
string y = x.OrIfEmpty("test");
Console.WriteLine(y); // "test"
You could probably choose a better name for OrIfEmpty() depending on taste.
However, note that this suffers from the drawback that the default value is always evaluated. If obtaining the default is expensive, then using this extension method will hurt performance because the default will always be evaluated even if it's not used.
To circumvent that issue you'd add an extension method to allow you to pass a Func<string> instead:
public static string OrIfEmpty(this string? self, Func<string> defaultValue)
{
return !string.IsNullOrEmpty(self) ? self : defaultValue();
}
Then when calling it you'd have to pass a delegate for the default, e.g:
public sealed class Program
{
public static void Main()
{
string? x = null;
string y = x.OrIfEmpty(expensiveDefault);
Console.WriteLine(y);
}
static string expensiveDefault()
{
return "test";
}
}
I'm just posting this for consideration. Myself, I would just use Marco's answer. But if you have a LOT of code that does it, then just maybe...

why dont nullable strings have a hasValue() method?

I have a class which contains a nullable strings, I want to make a check to see whether they stay null or somebody has set them.
simliar to strings, the class contains integers which are nullable, where i can perform this check by doing an equality comparison
with the .HasValue() method - it seems like strings dont have this?
So how do check whether it goes from null to notNull?
public class Test
{
public string? a
public string? b
public int? c
}
var oldQ = new Test(c=123)
var newQ = new Test(c=546)
bool isStilValid = newQ.c.HasValue() == oldQ.c.HasValue() //(this is not possible?)&& newQ.b.HasValue() == oldQ.b.HasValue()
why is this not possible?
HasValue property belongs to Nullable<T> struct, where T is also restricted to be a value type only. So, HasValue is exist only for value types.
Nullable reference types are implemented using type annotations, you can't use the same approach with nullable value types. To check a reference type for nullability you could use comparison with null or IsNullOrEmpty method (for strings only). So, you can rewrite your code a little bit
var oldQ = new Test() { c = 123 };
var newQ = new Test() { c = 456 };
bool isStilValid = string.IsNullOrEmpty(newQ.b) == string.IsNullOrEmpty(oldQ.b);
Or just use a regular comparison with null
bool isStilValid = (newQ.b != null) == (oldQ.b != null);
Only struct in C# have HasValue method, but you can simple create your own string extension as below and that will solve your problem.
public static class StringExtension {
public static bool HasValue(this string value)
{
return !string.IsNullOrEmpty(value);
}
}
I hope this is helpful for someone.
The equivalent comparing to null would be:
bool isStillValid = (newQ.c != null) == (oldQ.c != null) && (newQ.b != null) == (oldQ.b != null);
That's the equivalent to your original code, but I'm not sure the original code is correct...
isStillValid will be true if ALL the items being tested for null are actually null. Is that really what you intended?
That is, if newQ.c is null and oldQ.c is null and newQ.b is null and oldQ.b is null then isStillValid will be true.
The Nullable<T> type requires a type T that is a non-nullable value type for example int or double.
string typed variables are already null, so the nullable string typed variable doesn't make sense.
You need to use string.IsNullOrEmpty or simply null

How are you supposed to write attributes with null values in XML

Im using linq to xml to write out a little config file for an application and was a little surprised to discover XAttributes dont accept null as their value - they throw an exception instead.
Null is a perfectly valid value for many of the properties in my config and I dont want to have to null check attributes everywhere:
var attribute = _element.Attribute(attribute);
var value = attribute == null ? null : attribute.Value;
A further reason I dont want to write code like this is that it will make it easier to mis type names of things - eg if an attribute is spelled wrong it will just act like an attribute that exists but has a null value rather than throwing an exception.
The solution I have at the moment is as follows but it seems a little bit ugly + like something you shouldnt need to do.
I've knocked up a little class to make it a bit easier to write + read xml and am using a string containing just the null character to signal a null string.
I've omitted everything except the indexer for brevity:
public class XContainerWrapper
{
private readonly XElement _element;
public XContainerWrapper(XElement xElement)
{
_element = xElement;
}
public string this[string attribute]
{
get
{
var value = _element.Attribute(attribute).Value;
return value == "\0" ? null : value;
}
set
{
var valueToWrite = value ?? "\0";
_element.Add(new XAttribute(attribute, valueToWrite));
}
}
}
You can write your own extension method instead of XAttribute Value getter:
public static class XmlExtensions {
public static string SafeValue(this XAttribute attribute) {
var value = attribute == null ? null : attribute.Value;
return value;
}
}
Then you can use
XAttribute a = null;
var value = a.SafeValue();

handling nulls in c#

I have an object like this:
class MyObject
{
public string Object.Prop1 { get; set; }
public string Object.Prop2 { get; set; }
}
I'm writing a custom JSON converter and I'm serializing this object like this:
Dictionary<string, object> OutputJson = new Dictionary<string, object>();
OutputJson.Add("TheProp1", MyObject.Prop1.Trim());
If for some reason Prop1 is null, will the code encode TheProp1 as "" or will it crash?
If Prop1 is null your code will throw a NullReferenceException. You need to test if Prop1 is null before calling Trim:
MyObject.Prop1 == null ? "" : MyObject.Prop1.Trim()
Or you can do it more concisely with the null-coalescing operator:
(MyObject.Prop1 ?? "").Trim()
Another way to handle this is to use private member to handle the property values of properties where you need a default value rather than null
Class MyObject
{
private string _prop1 = String.Empty;
public string Object.Prop1 {
get
{
return _prop1;
}
set
{
_prop1 = value;
}
}
}
It will crash with a NullReferenceException, since you can't call Trim on null. You could do this instead:
OutputJson.Add("TheProp1", MyObject.Prop1 == null ?
string.Empty :
MyObject.Prop1.Trim());
My understanding is that a null is not an empty string. If you want to insure that this is going to work simply wrap the Value of the add in an if and insert your empty string as the null place holder. Of course you'll need to take the appropriate action when you decode your json.
If you don't need polymorphic behaviour for MyObject you can declare it as a struct instead of a class. It will have value semantic and every value will be initialize using its default. I am assuming inside your class you have just struct type (eg. int, string, double).
you can use DBNull class in filling the object
UserName = DBNull.Value != reader["UserName"] ? reader["UserName"].ToString() : default(string);

Possible to overload null-coalescing operator?

Is it possible to overload the null-coalescing operator for a class in C#?
Say for example I want to return a default value if an instance is null and return the instance if it's not. The code would look like something like this:
return instance ?? new MyClass("Default");
But what if I would like to use the null-coalescing operator to also check if the MyClass.MyValue is set?
Good question! It's not listed one way or another in the list of overloadable and non-overloadable operators and nothing's mentioned on the operator's page.
So I tried the following:
public class TestClass
{
public static TestClass operator ??(TestClass test1, TestClass test2)
{
return test1;
}
}
and I get the error "Overloadable binary operator expected". So I'd say the answer is, as of .NET 3.5, a no.
According to the ECMA-334 standard, it is not possible to overload the ?? operator.
Similarly, you cannot overload the following operators:
=
&&
||
?:
?.
checked
unchecked
new
typeof
as
is
Simple answer: No
C# design principles do not allow operator overloading that change semantics of the language. Therefore complex operators such as compound assignment, ternary operator and ... can not be overloaded.
This is rumored to be part of the next version of C#. From http://damieng.com/blog/2013/12/09/probable-c-6-0-features-illustrated
7. Monadic null checking
Removes the need to check for nulls before accessing properties or methods. Known as the Safe Navigation Operator in Groovy).
Before
if (points != null) {
var next = points.FirstOrDefault();
if (next != null && next.X != null) return next.X;
}
return -1;
After
var bestValue = points?.FirstOrDefault()?.X ?? -1;
I was trying to accomplish this with a struct I wrote that was very similar Nullable<T>. With Nullable<T> you can do something like
Nullable<Guid> id1 = null;
Guid id2 = id1 ?? Guid.NewGuid();
It has no problem implicitly converting id1 from Nullable<Guid> to a Guid despite the fact that Nullable<T> only defines an explicit conversion to type T. Doing the same thing with my own type, it gives an error
Operator '??' cannot be applied to operands of type 'MyType' and
'Guid'
So I think there's some magic built into the compiler to make a special exception for Nullable<T>. So as an alternative...
tl;dr
We can't override the ?? operator, but if you want the coalesce operator to evaluate an underlying value rather than the class (or struct in my case) itself, you could just use a method resulting in very few extra keystrokes required. With my case above it looks something like this:
public struct MyType<T>
{
private bool _hasValue;
internal T _value;
public MyType(T value)
{
this._value = value;
this._hasValue = true;
}
public T Or(T altValue)
{
if (this._hasValue)
return this._value;
else
return altValue;
}
}
Usage:
MyType<Guid> id1 = null;
Guid id2 = id1.Or(Guid.Empty);
This works well since it's a struct and id1 itself can't actually be null. For a class, an extension method could handle if the instance is null as long as the value you're trying to check is exposed:
public class MyClass
{
public MyClass(string myValue)
{
MyValue = myValue;
}
public string MyValue { get; set; }
}
public static class MyClassExtensions
{
public static string Or(this MyClass myClass, string altVal)
{
if (myClass != null && myClass.MyValue != null)
return myClass.MyValue;
else
return altVal;
}
}
Usage:
MyClass mc1 = new MyClass(null);
string requiredVal = mc1.Or("default"); //Instead of mc1 ?? "default";
If anyone is here looking for a solution, the closest example would be to do this
return instance.MyValue != null ? instance : new MyClass("Default");

Categories

Resources