Empty string if null
I have this in my code:
SelectList(blah, "blah", "blah", cu.Customer.CustomerID.ToString())
It gives a error when it returns null, how can I make it CustomerID is an empty string if it is null?
/M
c# asp.net-mvc
add a comment |
I have this in my code:
SelectList(blah, "blah", "blah", cu.Customer.CustomerID.ToString())
It gives a error when it returns null, how can I make it CustomerID is an empty string if it is null?
/M
c# asp.net-mvc
1
IsCustomerID
the null value, or is theCustomer
itself null? Also, what is the type ofCustomerID
?
– Thorarin
Nov 2 '09 at 9:52
add a comment |
I have this in my code:
SelectList(blah, "blah", "blah", cu.Customer.CustomerID.ToString())
It gives a error when it returns null, how can I make it CustomerID is an empty string if it is null?
/M
c# asp.net-mvc
I have this in my code:
SelectList(blah, "blah", "blah", cu.Customer.CustomerID.ToString())
It gives a error when it returns null, how can I make it CustomerID is an empty string if it is null?
/M
c# asp.net-mvc
c# asp.net-mvc
asked Nov 2 '09 at 9:41
Lasse Edsvik
4,420135997
4,420135997
1
IsCustomerID
the null value, or is theCustomer
itself null? Also, what is the type ofCustomerID
?
– Thorarin
Nov 2 '09 at 9:52
add a comment |
1
IsCustomerID
the null value, or is theCustomer
itself null? Also, what is the type ofCustomerID
?
– Thorarin
Nov 2 '09 at 9:52
1
1
Is
CustomerID
the null value, or is the Customer
itself null? Also, what is the type of CustomerID
?– Thorarin
Nov 2 '09 at 9:52
Is
CustomerID
the null value, or is the Customer
itself null? Also, what is the type of CustomerID
?– Thorarin
Nov 2 '09 at 9:52
add a comment |
5 Answers
5
active
oldest
votes
(Update for C# 6.0)
If you are using C# 6 or newer (Visual Studio 2015 or newer), then you can achieve this using the null-conditional operator ?.
:
var customerId = cu.Customer?.CustomerId.ToString() ?? "";
One useful property of the null-conditional operator is that it can also be "chained" if you want to test if several nested properties are null:
// ensure (a != null) && (b != null) && (c != null) before invoking
// a.b.c.CustomerId, otherwise return "" (short circuited at first encountered null)
var customerId = a?.b?.c?.CustomerId.ToString() ?? "";
For C# versions prior to 6.0 (VS2013 or older), you could coalesce it like this:
string customerId = cu.Customer != null ? cu.Customer.CustomerID.ToString() : "";
Simply check if the object is non-null before you try to access its members, and return an empty string otherwise.
Apart from that, there are situations where null object pattern is useful. That would mean that you ensure that your Customer
's parent class (type of cu
in this case) always return an actual instance of an object, even if it is "Empty". Check this link for an example, if you think it may apply to your problem: How do I create a Null Object in C#.
add a comment |
It depends of the type of CustomerID
.
If CustomerID
is a string then you can use the null coalescing operator:
SelectList(blah, "blah", "blah", cu.Customer.CustomerID ?? string.Empty)
If CustomerID
is a Nullable<T>
, then you can use:
SelectList(blah, "blah", "blah", cu.Customer.CustomerID.ToString())
This will work because the ToString()
method of Nullable<T>
returns an empty string if the instance is null
(technically if the HasValue property is false
).
add a comment |
(C# 2.0 - C# 5.0)
The ternary operator works, but if you want even shorter expression working on arbitrary objects you can use:
(myObject ?? "").ToString()
Here is real-life example from my code:
private HtmlTableCell CreateTableCell(object cellContents)
{
return new HtmlTableCell()
{
InnerText = (cellContents ?? "").ToString()
};
}
One of the outcomes of this code is redundant"".ToString()
, moreover(myObject ?? "")
will work only ifmyObject
was a string in the first place, making.ToString()
even more unnecessary. I think you meantmyObject?.ToString() ?? ""
.
– ensisNoctis
Nov 2 '18 at 20:24
1
@ensisNoctis 1. This was written at the time we had C# 5, which didn't have?.
operator. For C# 6+, I'd use?.
. 2..ToString()
works on objects just fine. I stand by my answer scoped to C# 2 - C# 5: updated to clarify.
– DKroot
Nov 19 '18 at 17:27
Fine with me :)
– ensisNoctis
Nov 20 '18 at 12:05
add a comment |
SelectList(blah, "blah", "blah",
(cu.Customer.CustomerID!=null?cu.Customer.CustomerID.ToString():"")
)
add a comment |
Please don't use this in production :
/// <summary>
/// I most certainly don't recommend using this in production but when one can abuse delegates, one should :)
/// </summary>
public static class DirtyHelpers
{
public static TVal SafeGet<THolder, TVal>(this THolder holder, Func<TVal> extract) where THolder : class
{
return null == holder ? default(TVal) : extract();
}
public static void Sample(String name)
{
int len = name.SafeGet(()=> name.Length);
}
}
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1660269%2fempty-string-if-null%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
5 Answers
5
active
oldest
votes
5 Answers
5
active
oldest
votes
active
oldest
votes
active
oldest
votes
(Update for C# 6.0)
If you are using C# 6 or newer (Visual Studio 2015 or newer), then you can achieve this using the null-conditional operator ?.
:
var customerId = cu.Customer?.CustomerId.ToString() ?? "";
One useful property of the null-conditional operator is that it can also be "chained" if you want to test if several nested properties are null:
// ensure (a != null) && (b != null) && (c != null) before invoking
// a.b.c.CustomerId, otherwise return "" (short circuited at first encountered null)
var customerId = a?.b?.c?.CustomerId.ToString() ?? "";
For C# versions prior to 6.0 (VS2013 or older), you could coalesce it like this:
string customerId = cu.Customer != null ? cu.Customer.CustomerID.ToString() : "";
Simply check if the object is non-null before you try to access its members, and return an empty string otherwise.
Apart from that, there are situations where null object pattern is useful. That would mean that you ensure that your Customer
's parent class (type of cu
in this case) always return an actual instance of an object, even if it is "Empty". Check this link for an example, if you think it may apply to your problem: How do I create a Null Object in C#.
add a comment |
(Update for C# 6.0)
If you are using C# 6 or newer (Visual Studio 2015 or newer), then you can achieve this using the null-conditional operator ?.
:
var customerId = cu.Customer?.CustomerId.ToString() ?? "";
One useful property of the null-conditional operator is that it can also be "chained" if you want to test if several nested properties are null:
// ensure (a != null) && (b != null) && (c != null) before invoking
// a.b.c.CustomerId, otherwise return "" (short circuited at first encountered null)
var customerId = a?.b?.c?.CustomerId.ToString() ?? "";
For C# versions prior to 6.0 (VS2013 or older), you could coalesce it like this:
string customerId = cu.Customer != null ? cu.Customer.CustomerID.ToString() : "";
Simply check if the object is non-null before you try to access its members, and return an empty string otherwise.
Apart from that, there are situations where null object pattern is useful. That would mean that you ensure that your Customer
's parent class (type of cu
in this case) always return an actual instance of an object, even if it is "Empty". Check this link for an example, if you think it may apply to your problem: How do I create a Null Object in C#.
add a comment |
(Update for C# 6.0)
If you are using C# 6 or newer (Visual Studio 2015 or newer), then you can achieve this using the null-conditional operator ?.
:
var customerId = cu.Customer?.CustomerId.ToString() ?? "";
One useful property of the null-conditional operator is that it can also be "chained" if you want to test if several nested properties are null:
// ensure (a != null) && (b != null) && (c != null) before invoking
// a.b.c.CustomerId, otherwise return "" (short circuited at first encountered null)
var customerId = a?.b?.c?.CustomerId.ToString() ?? "";
For C# versions prior to 6.0 (VS2013 or older), you could coalesce it like this:
string customerId = cu.Customer != null ? cu.Customer.CustomerID.ToString() : "";
Simply check if the object is non-null before you try to access its members, and return an empty string otherwise.
Apart from that, there are situations where null object pattern is useful. That would mean that you ensure that your Customer
's parent class (type of cu
in this case) always return an actual instance of an object, even if it is "Empty". Check this link for an example, if you think it may apply to your problem: How do I create a Null Object in C#.
(Update for C# 6.0)
If you are using C# 6 or newer (Visual Studio 2015 or newer), then you can achieve this using the null-conditional operator ?.
:
var customerId = cu.Customer?.CustomerId.ToString() ?? "";
One useful property of the null-conditional operator is that it can also be "chained" if you want to test if several nested properties are null:
// ensure (a != null) && (b != null) && (c != null) before invoking
// a.b.c.CustomerId, otherwise return "" (short circuited at first encountered null)
var customerId = a?.b?.c?.CustomerId.ToString() ?? "";
For C# versions prior to 6.0 (VS2013 or older), you could coalesce it like this:
string customerId = cu.Customer != null ? cu.Customer.CustomerID.ToString() : "";
Simply check if the object is non-null before you try to access its members, and return an empty string otherwise.
Apart from that, there are situations where null object pattern is useful. That would mean that you ensure that your Customer
's parent class (type of cu
in this case) always return an actual instance of an object, even if it is "Empty". Check this link for an example, if you think it may apply to your problem: How do I create a Null Object in C#.
edited May 23 '17 at 12:32
Community♦
11
11
answered Nov 2 '09 at 9:43
Groo
35.2k1483158
35.2k1483158
add a comment |
add a comment |
It depends of the type of CustomerID
.
If CustomerID
is a string then you can use the null coalescing operator:
SelectList(blah, "blah", "blah", cu.Customer.CustomerID ?? string.Empty)
If CustomerID
is a Nullable<T>
, then you can use:
SelectList(blah, "blah", "blah", cu.Customer.CustomerID.ToString())
This will work because the ToString()
method of Nullable<T>
returns an empty string if the instance is null
(technically if the HasValue property is false
).
add a comment |
It depends of the type of CustomerID
.
If CustomerID
is a string then you can use the null coalescing operator:
SelectList(blah, "blah", "blah", cu.Customer.CustomerID ?? string.Empty)
If CustomerID
is a Nullable<T>
, then you can use:
SelectList(blah, "blah", "blah", cu.Customer.CustomerID.ToString())
This will work because the ToString()
method of Nullable<T>
returns an empty string if the instance is null
(technically if the HasValue property is false
).
add a comment |
It depends of the type of CustomerID
.
If CustomerID
is a string then you can use the null coalescing operator:
SelectList(blah, "blah", "blah", cu.Customer.CustomerID ?? string.Empty)
If CustomerID
is a Nullable<T>
, then you can use:
SelectList(blah, "blah", "blah", cu.Customer.CustomerID.ToString())
This will work because the ToString()
method of Nullable<T>
returns an empty string if the instance is null
(technically if the HasValue property is false
).
It depends of the type of CustomerID
.
If CustomerID
is a string then you can use the null coalescing operator:
SelectList(blah, "blah", "blah", cu.Customer.CustomerID ?? string.Empty)
If CustomerID
is a Nullable<T>
, then you can use:
SelectList(blah, "blah", "blah", cu.Customer.CustomerID.ToString())
This will work because the ToString()
method of Nullable<T>
returns an empty string if the instance is null
(technically if the HasValue property is false
).
edited Nov 2 '09 at 10:02
answered Nov 2 '09 at 9:49
adrianbanks
65.6k18142181
65.6k18142181
add a comment |
add a comment |
(C# 2.0 - C# 5.0)
The ternary operator works, but if you want even shorter expression working on arbitrary objects you can use:
(myObject ?? "").ToString()
Here is real-life example from my code:
private HtmlTableCell CreateTableCell(object cellContents)
{
return new HtmlTableCell()
{
InnerText = (cellContents ?? "").ToString()
};
}
One of the outcomes of this code is redundant"".ToString()
, moreover(myObject ?? "")
will work only ifmyObject
was a string in the first place, making.ToString()
even more unnecessary. I think you meantmyObject?.ToString() ?? ""
.
– ensisNoctis
Nov 2 '18 at 20:24
1
@ensisNoctis 1. This was written at the time we had C# 5, which didn't have?.
operator. For C# 6+, I'd use?.
. 2..ToString()
works on objects just fine. I stand by my answer scoped to C# 2 - C# 5: updated to clarify.
– DKroot
Nov 19 '18 at 17:27
Fine with me :)
– ensisNoctis
Nov 20 '18 at 12:05
add a comment |
(C# 2.0 - C# 5.0)
The ternary operator works, but if you want even shorter expression working on arbitrary objects you can use:
(myObject ?? "").ToString()
Here is real-life example from my code:
private HtmlTableCell CreateTableCell(object cellContents)
{
return new HtmlTableCell()
{
InnerText = (cellContents ?? "").ToString()
};
}
One of the outcomes of this code is redundant"".ToString()
, moreover(myObject ?? "")
will work only ifmyObject
was a string in the first place, making.ToString()
even more unnecessary. I think you meantmyObject?.ToString() ?? ""
.
– ensisNoctis
Nov 2 '18 at 20:24
1
@ensisNoctis 1. This was written at the time we had C# 5, which didn't have?.
operator. For C# 6+, I'd use?.
. 2..ToString()
works on objects just fine. I stand by my answer scoped to C# 2 - C# 5: updated to clarify.
– DKroot
Nov 19 '18 at 17:27
Fine with me :)
– ensisNoctis
Nov 20 '18 at 12:05
add a comment |
(C# 2.0 - C# 5.0)
The ternary operator works, but if you want even shorter expression working on arbitrary objects you can use:
(myObject ?? "").ToString()
Here is real-life example from my code:
private HtmlTableCell CreateTableCell(object cellContents)
{
return new HtmlTableCell()
{
InnerText = (cellContents ?? "").ToString()
};
}
(C# 2.0 - C# 5.0)
The ternary operator works, but if you want even shorter expression working on arbitrary objects you can use:
(myObject ?? "").ToString()
Here is real-life example from my code:
private HtmlTableCell CreateTableCell(object cellContents)
{
return new HtmlTableCell()
{
InnerText = (cellContents ?? "").ToString()
};
}
edited Nov 19 '18 at 17:24
answered Jan 20 '15 at 20:01
DKroot
756617
756617
One of the outcomes of this code is redundant"".ToString()
, moreover(myObject ?? "")
will work only ifmyObject
was a string in the first place, making.ToString()
even more unnecessary. I think you meantmyObject?.ToString() ?? ""
.
– ensisNoctis
Nov 2 '18 at 20:24
1
@ensisNoctis 1. This was written at the time we had C# 5, which didn't have?.
operator. For C# 6+, I'd use?.
. 2..ToString()
works on objects just fine. I stand by my answer scoped to C# 2 - C# 5: updated to clarify.
– DKroot
Nov 19 '18 at 17:27
Fine with me :)
– ensisNoctis
Nov 20 '18 at 12:05
add a comment |
One of the outcomes of this code is redundant"".ToString()
, moreover(myObject ?? "")
will work only ifmyObject
was a string in the first place, making.ToString()
even more unnecessary. I think you meantmyObject?.ToString() ?? ""
.
– ensisNoctis
Nov 2 '18 at 20:24
1
@ensisNoctis 1. This was written at the time we had C# 5, which didn't have?.
operator. For C# 6+, I'd use?.
. 2..ToString()
works on objects just fine. I stand by my answer scoped to C# 2 - C# 5: updated to clarify.
– DKroot
Nov 19 '18 at 17:27
Fine with me :)
– ensisNoctis
Nov 20 '18 at 12:05
One of the outcomes of this code is redundant
"".ToString()
, moreover (myObject ?? "")
will work only if myObject
was a string in the first place, making .ToString()
even more unnecessary. I think you meant myObject?.ToString() ?? ""
.– ensisNoctis
Nov 2 '18 at 20:24
One of the outcomes of this code is redundant
"".ToString()
, moreover (myObject ?? "")
will work only if myObject
was a string in the first place, making .ToString()
even more unnecessary. I think you meant myObject?.ToString() ?? ""
.– ensisNoctis
Nov 2 '18 at 20:24
1
1
@ensisNoctis 1. This was written at the time we had C# 5, which didn't have
?.
operator. For C# 6+, I'd use ?.
. 2. .ToString()
works on objects just fine. I stand by my answer scoped to C# 2 - C# 5: updated to clarify.– DKroot
Nov 19 '18 at 17:27
@ensisNoctis 1. This was written at the time we had C# 5, which didn't have
?.
operator. For C# 6+, I'd use ?.
. 2. .ToString()
works on objects just fine. I stand by my answer scoped to C# 2 - C# 5: updated to clarify.– DKroot
Nov 19 '18 at 17:27
Fine with me :)
– ensisNoctis
Nov 20 '18 at 12:05
Fine with me :)
– ensisNoctis
Nov 20 '18 at 12:05
add a comment |
SelectList(blah, "blah", "blah",
(cu.Customer.CustomerID!=null?cu.Customer.CustomerID.ToString():"")
)
add a comment |
SelectList(blah, "blah", "blah",
(cu.Customer.CustomerID!=null?cu.Customer.CustomerID.ToString():"")
)
add a comment |
SelectList(blah, "blah", "blah",
(cu.Customer.CustomerID!=null?cu.Customer.CustomerID.ToString():"")
)
SelectList(blah, "blah", "blah",
(cu.Customer.CustomerID!=null?cu.Customer.CustomerID.ToString():"")
)
answered Nov 2 '09 at 9:44
Palantir
18k86380
18k86380
add a comment |
add a comment |
Please don't use this in production :
/// <summary>
/// I most certainly don't recommend using this in production but when one can abuse delegates, one should :)
/// </summary>
public static class DirtyHelpers
{
public static TVal SafeGet<THolder, TVal>(this THolder holder, Func<TVal> extract) where THolder : class
{
return null == holder ? default(TVal) : extract();
}
public static void Sample(String name)
{
int len = name.SafeGet(()=> name.Length);
}
}
add a comment |
Please don't use this in production :
/// <summary>
/// I most certainly don't recommend using this in production but when one can abuse delegates, one should :)
/// </summary>
public static class DirtyHelpers
{
public static TVal SafeGet<THolder, TVal>(this THolder holder, Func<TVal> extract) where THolder : class
{
return null == holder ? default(TVal) : extract();
}
public static void Sample(String name)
{
int len = name.SafeGet(()=> name.Length);
}
}
add a comment |
Please don't use this in production :
/// <summary>
/// I most certainly don't recommend using this in production but when one can abuse delegates, one should :)
/// </summary>
public static class DirtyHelpers
{
public static TVal SafeGet<THolder, TVal>(this THolder holder, Func<TVal> extract) where THolder : class
{
return null == holder ? default(TVal) : extract();
}
public static void Sample(String name)
{
int len = name.SafeGet(()=> name.Length);
}
}
Please don't use this in production :
/// <summary>
/// I most certainly don't recommend using this in production but when one can abuse delegates, one should :)
/// </summary>
public static class DirtyHelpers
{
public static TVal SafeGet<THolder, TVal>(this THolder holder, Func<TVal> extract) where THolder : class
{
return null == holder ? default(TVal) : extract();
}
public static void Sample(String name)
{
int len = name.SafeGet(()=> name.Length);
}
}
answered Nov 2 '09 at 11:34
Florian Doyon
3,2181931
3,2181931
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1660269%2fempty-string-if-null%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
Is
CustomerID
the null value, or is theCustomer
itself null? Also, what is the type ofCustomerID
?– Thorarin
Nov 2 '09 at 9:52