Type int? vs type intNullable<int> vs. int? - Is there any difference?How is the boxing/unboxing behavior of Nullable<T> possible?Cast int to enum in C#Create Generic method constraining T to an EnumRandom number generator only generating one random numberUsing LINQ to remove elements from a List<T>Get int value from enum in C#Type Checking: typeof, GetType, or is?Distinct() with lambda?How do I generate a random int number?Call one constructor from anotherTry-catch speeding up my code?
Can a German sentence have two subjects?
Motorized valve interfering with button?
Why is this code 6.5x slower with optimizations enabled?
Is it tax fraud for an individual to declare non-taxable revenue as taxable income? (US tax laws)
Can I make popcorn with any corn?
I probably found a bug with the sudo apt install function
black dwarf stars and dark matter
How can the DM most effectively choose 1 out of an odd number of players to be targeted by an attack or effect?
How is the claim "I am in New York only if I am in America" the same as "If I am in New York, then I am in America?
How does one intimidate enemies without having the capacity for violence?
Prevent a directory in /tmp from being deleted
Why are only specific transaction types accepted into the mempool?
How do we improve the relationship with a client software team that performs poorly and is becoming less collaborative?
Why is an old chain unsafe?
Copycat chess is back
Email Account under attack (really) - anything I can do?
Can I interfere when another PC is about to be attacked?
Why CLRS example on residual networks does not follows its formula?
A Journey Through Space and Time
What do you call a Matrix-like slowdown and camera movement effect?
How to add power-LED to my small amplifier?
A newer friend of my brother's gave him a load of baseball cards that are supposedly extremely valuable. Is this a scam?
What typically incentivizes a professor to change jobs to a lower ranking university?
What is the meaning of "of trouble" in the following sentence?
Type int? vs type int
Nullable<int> vs. int? - Is there any difference?How is the boxing/unboxing behavior of Nullable<T> possible?Cast int to enum in C#Create Generic method constraining T to an EnumRandom number generator only generating one random numberUsing LINQ to remove elements from a List<T>Get int value from enum in C#Type Checking: typeof, GetType, or is?Distinct() with lambda?How do I generate a random int number?Call one constructor from anotherTry-catch speeding up my code?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I've this comparison which equals false
as expected
bool eq = typeof(int?).Equals(typeof(int));
now I have this code
List<object> items = new List<object>() (int?)123 ;
int result = items.OfType<int>().FirstOrDefault();
but this returns 123
- anyway that value is of type int?
How can this be?
c# casting
|
show 2 more comments
I've this comparison which equals false
as expected
bool eq = typeof(int?).Equals(typeof(int));
now I have this code
List<object> items = new List<object>() (int?)123 ;
int result = items.OfType<int>().FirstOrDefault();
but this returns 123
- anyway that value is of type int?
How can this be?
c# casting
int?
boxed asint
, and basically every Nullable type, Edit : Marc Gravell have the full answer
– styx
Mar 27 at 8:30
Related post about nullable type: stackoverflow.com/questions/4028830/…. This is called as "type lifting".
– Tetsuya Yamamoto
Mar 27 at 8:32
Before reading this topic I wouldn't even guess that evenList<int?>
already holds justint
types. Proof
– Sinatr
Mar 27 at 8:46
7
@Sinatr no, that is incorrect;List<int?>
holdsint?
. The important distinction in this example is the use ofList<object>
. What you're seeing in that "proof" is something very different;GetType()
on anyT?
either returns theT
, or throws a NRE. It never returnsT?
- better example: dotnetfiddle.net/3Gy3Fa - and as for why: becauseGetType()
is non-virtual, it cannot be overridden, and thus callingGetType()
is a boxing operation (even if used via "constrained call"). And when you box aT?
, you either get aT
as anobject
, or anull
.
– Marc Gravell♦
Mar 27 at 8:49
@TetsuyaYamamoto That is not a relevant link. How is the boxing/unboxing behavior of Nullable<T> possible? is.
– GSerg
Mar 27 at 11:17
|
show 2 more comments
I've this comparison which equals false
as expected
bool eq = typeof(int?).Equals(typeof(int));
now I have this code
List<object> items = new List<object>() (int?)123 ;
int result = items.OfType<int>().FirstOrDefault();
but this returns 123
- anyway that value is of type int?
How can this be?
c# casting
I've this comparison which equals false
as expected
bool eq = typeof(int?).Equals(typeof(int));
now I have this code
List<object> items = new List<object>() (int?)123 ;
int result = items.OfType<int>().FirstOrDefault();
but this returns 123
- anyway that value is of type int?
How can this be?
c# casting
c# casting
asked Mar 27 at 8:27
Dr. SnailDr. Snail
768828
768828
int?
boxed asint
, and basically every Nullable type, Edit : Marc Gravell have the full answer
– styx
Mar 27 at 8:30
Related post about nullable type: stackoverflow.com/questions/4028830/…. This is called as "type lifting".
– Tetsuya Yamamoto
Mar 27 at 8:32
Before reading this topic I wouldn't even guess that evenList<int?>
already holds justint
types. Proof
– Sinatr
Mar 27 at 8:46
7
@Sinatr no, that is incorrect;List<int?>
holdsint?
. The important distinction in this example is the use ofList<object>
. What you're seeing in that "proof" is something very different;GetType()
on anyT?
either returns theT
, or throws a NRE. It never returnsT?
- better example: dotnetfiddle.net/3Gy3Fa - and as for why: becauseGetType()
is non-virtual, it cannot be overridden, and thus callingGetType()
is a boxing operation (even if used via "constrained call"). And when you box aT?
, you either get aT
as anobject
, or anull
.
– Marc Gravell♦
Mar 27 at 8:49
@TetsuyaYamamoto That is not a relevant link. How is the boxing/unboxing behavior of Nullable<T> possible? is.
– GSerg
Mar 27 at 11:17
|
show 2 more comments
int?
boxed asint
, and basically every Nullable type, Edit : Marc Gravell have the full answer
– styx
Mar 27 at 8:30
Related post about nullable type: stackoverflow.com/questions/4028830/…. This is called as "type lifting".
– Tetsuya Yamamoto
Mar 27 at 8:32
Before reading this topic I wouldn't even guess that evenList<int?>
already holds justint
types. Proof
– Sinatr
Mar 27 at 8:46
7
@Sinatr no, that is incorrect;List<int?>
holdsint?
. The important distinction in this example is the use ofList<object>
. What you're seeing in that "proof" is something very different;GetType()
on anyT?
either returns theT
, or throws a NRE. It never returnsT?
- better example: dotnetfiddle.net/3Gy3Fa - and as for why: becauseGetType()
is non-virtual, it cannot be overridden, and thus callingGetType()
is a boxing operation (even if used via "constrained call"). And when you box aT?
, you either get aT
as anobject
, or anull
.
– Marc Gravell♦
Mar 27 at 8:49
@TetsuyaYamamoto That is not a relevant link. How is the boxing/unboxing behavior of Nullable<T> possible? is.
– GSerg
Mar 27 at 11:17
int?
boxed as int
, and basically every Nullable type, Edit : Marc Gravell have the full answer– styx
Mar 27 at 8:30
int?
boxed as int
, and basically every Nullable type, Edit : Marc Gravell have the full answer– styx
Mar 27 at 8:30
Related post about nullable type: stackoverflow.com/questions/4028830/…. This is called as "type lifting".
– Tetsuya Yamamoto
Mar 27 at 8:32
Related post about nullable type: stackoverflow.com/questions/4028830/…. This is called as "type lifting".
– Tetsuya Yamamoto
Mar 27 at 8:32
Before reading this topic I wouldn't even guess that even
List<int?>
already holds just int
types. Proof– Sinatr
Mar 27 at 8:46
Before reading this topic I wouldn't even guess that even
List<int?>
already holds just int
types. Proof– Sinatr
Mar 27 at 8:46
7
7
@Sinatr no, that is incorrect;
List<int?>
holds int?
. The important distinction in this example is the use of List<object>
. What you're seeing in that "proof" is something very different; GetType()
on any T?
either returns the T
, or throws a NRE. It never returns T?
- better example: dotnetfiddle.net/3Gy3Fa - and as for why: because GetType()
is non-virtual, it cannot be overridden, and thus calling GetType()
is a boxing operation (even if used via "constrained call"). And when you box a T?
, you either get a T
as an object
, or a null
.– Marc Gravell♦
Mar 27 at 8:49
@Sinatr no, that is incorrect;
List<int?>
holds int?
. The important distinction in this example is the use of List<object>
. What you're seeing in that "proof" is something very different; GetType()
on any T?
either returns the T
, or throws a NRE. It never returns T?
- better example: dotnetfiddle.net/3Gy3Fa - and as for why: because GetType()
is non-virtual, it cannot be overridden, and thus calling GetType()
is a boxing operation (even if used via "constrained call"). And when you box a T?
, you either get a T
as an object
, or a null
.– Marc Gravell♦
Mar 27 at 8:49
@TetsuyaYamamoto That is not a relevant link. How is the boxing/unboxing behavior of Nullable<T> possible? is.
– GSerg
Mar 27 at 11:17
@TetsuyaYamamoto That is not a relevant link. How is the boxing/unboxing behavior of Nullable<T> possible? is.
– GSerg
Mar 27 at 11:17
|
show 2 more comments
3 Answers
3
active
oldest
votes
Nullable types have special "boxing" rules; "boxing" is when a value-type is treated as object
, as per your code. Unlike regular value-types, a nullable value-type is boxed either as null
(regular null
, no type), or as the non-nullable type (the T
in T?
). So: an int?
is boxed as an int
, not an int?
. Then when you use OfType<int>()
on it, you get all the values that are int
, which is: the single value you passed in, since it is of type int
.
phew ok thank you for that explanaion. Is that C# basic knowledge?
– Dr. Snail
Mar 27 at 8:30
14
@Dr.Snail "basic" is relative / subjective, and I'd wager that a good percentage of developers never have a need to know that nuance; it is useful context if you're dealing with boxing, though... and technically it isn't really C# knowledge, but rather: .NET knowledge (it would apply to all languages)
– Marc Gravell♦
Mar 27 at 8:31
5
@Sinatr you can't - the list never containsint?
- it only containsint
because of the boxing rules on nullable types
– Marc Gravell♦
Mar 27 at 8:34
1
@KyleJohnson you added a nullable int to the list. Naively, if nullable ints and ints are different things, you'd expect asking for all the ints in the list to return nothing. There are languages that do it that way, but C# has chosen to do it differently.
– mbrig
Mar 27 at 21:24
1
(and yes, my first sentence there is technically wrong. The nullable int never got added to the list. But if you don't know what's happening here, that's what it looks like is happening)
– mbrig
Mar 27 at 21:26
|
show 2 more comments
A nullable value type is boxed by the following rules:
- If
HasValue
returnsfalse
, the null reference is produced. - If
HasValue
returnstrue
, a value of the underlying value typeT
is
boxed, not the instance of nullable.
In your example second rule has been followed as you have value, e.g. var i = (object)(int?)123;
add a comment |
It is a bit late, but beside of Marc's answer to your question, I want to give some additional information about Nullable value types in CLR.
The CLR has built-in support for nullable value types. This special support is provided for boxing, unboxing, calling GetType
, calling interface methods.
For example, let's check GetType()
:
Int32? x = 5;
Console.WriteLine(x.GetType());
What you think it will print to the console?System.Nullable<Int32
? Not, the result is System.Int32
.
Or, let's check boxing, which you noted in your question:
Int32? n =5;
Object o = n;
Console.WriteLine("o's type=0", o.GetType()); // "System.Int32"
The rule is that:
When the CLR is boxing a Nullable instance, it checks to see if it
is null, and if so, the CLR doesn’t actually box anything, and null is
returned. If the nullable instance is not null, the CLR takes the
value out of the nullable instance and boxes it. In other words, a
Nullable with a value of 5 is boxed into a boxed-Int32 with a
value of 5.
And, at the end I want to explain how CLR add special support for calling interface methods from Nullable Types.
Let's take a look to that:
Int32? n = 5;
Int32 result = ((IComparable) n).CompareTo(5); // Compiles & runs OK
Console.WriteLine(result); // 0
In the preceding code, I’m casting n, a Nullable<Int32>
, to IComparable<Int32>
, an interface
type. However, the Nullable<T>
type does not implement the IComparable<Int32>
interface asInt32
does. The C# compiler allows this code to compile anyway.
So, nullables have special treatment by the compiler? I couldn't implement these rules for my own type?
– Markonius
2 days ago
1
@Markonius For example you can not overrideGetType
for your own type to lie about the real type of your object. Because,GetType
is non-virtual.
– Farhad Jabiyev
2 days ago
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%2f55372675%2ftype-int-vs-type-int%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
Nullable types have special "boxing" rules; "boxing" is when a value-type is treated as object
, as per your code. Unlike regular value-types, a nullable value-type is boxed either as null
(regular null
, no type), or as the non-nullable type (the T
in T?
). So: an int?
is boxed as an int
, not an int?
. Then when you use OfType<int>()
on it, you get all the values that are int
, which is: the single value you passed in, since it is of type int
.
phew ok thank you for that explanaion. Is that C# basic knowledge?
– Dr. Snail
Mar 27 at 8:30
14
@Dr.Snail "basic" is relative / subjective, and I'd wager that a good percentage of developers never have a need to know that nuance; it is useful context if you're dealing with boxing, though... and technically it isn't really C# knowledge, but rather: .NET knowledge (it would apply to all languages)
– Marc Gravell♦
Mar 27 at 8:31
5
@Sinatr you can't - the list never containsint?
- it only containsint
because of the boxing rules on nullable types
– Marc Gravell♦
Mar 27 at 8:34
1
@KyleJohnson you added a nullable int to the list. Naively, if nullable ints and ints are different things, you'd expect asking for all the ints in the list to return nothing. There are languages that do it that way, but C# has chosen to do it differently.
– mbrig
Mar 27 at 21:24
1
(and yes, my first sentence there is technically wrong. The nullable int never got added to the list. But if you don't know what's happening here, that's what it looks like is happening)
– mbrig
Mar 27 at 21:26
|
show 2 more comments
Nullable types have special "boxing" rules; "boxing" is when a value-type is treated as object
, as per your code. Unlike regular value-types, a nullable value-type is boxed either as null
(regular null
, no type), or as the non-nullable type (the T
in T?
). So: an int?
is boxed as an int
, not an int?
. Then when you use OfType<int>()
on it, you get all the values that are int
, which is: the single value you passed in, since it is of type int
.
phew ok thank you for that explanaion. Is that C# basic knowledge?
– Dr. Snail
Mar 27 at 8:30
14
@Dr.Snail "basic" is relative / subjective, and I'd wager that a good percentage of developers never have a need to know that nuance; it is useful context if you're dealing with boxing, though... and technically it isn't really C# knowledge, but rather: .NET knowledge (it would apply to all languages)
– Marc Gravell♦
Mar 27 at 8:31
5
@Sinatr you can't - the list never containsint?
- it only containsint
because of the boxing rules on nullable types
– Marc Gravell♦
Mar 27 at 8:34
1
@KyleJohnson you added a nullable int to the list. Naively, if nullable ints and ints are different things, you'd expect asking for all the ints in the list to return nothing. There are languages that do it that way, but C# has chosen to do it differently.
– mbrig
Mar 27 at 21:24
1
(and yes, my first sentence there is technically wrong. The nullable int never got added to the list. But if you don't know what's happening here, that's what it looks like is happening)
– mbrig
Mar 27 at 21:26
|
show 2 more comments
Nullable types have special "boxing" rules; "boxing" is when a value-type is treated as object
, as per your code. Unlike regular value-types, a nullable value-type is boxed either as null
(regular null
, no type), or as the non-nullable type (the T
in T?
). So: an int?
is boxed as an int
, not an int?
. Then when you use OfType<int>()
on it, you get all the values that are int
, which is: the single value you passed in, since it is of type int
.
Nullable types have special "boxing" rules; "boxing" is when a value-type is treated as object
, as per your code. Unlike regular value-types, a nullable value-type is boxed either as null
(regular null
, no type), or as the non-nullable type (the T
in T?
). So: an int?
is boxed as an int
, not an int?
. Then when you use OfType<int>()
on it, you get all the values that are int
, which is: the single value you passed in, since it is of type int
.
answered Mar 27 at 8:28
Marc Gravell♦Marc Gravell
794k19821612565
794k19821612565
phew ok thank you for that explanaion. Is that C# basic knowledge?
– Dr. Snail
Mar 27 at 8:30
14
@Dr.Snail "basic" is relative / subjective, and I'd wager that a good percentage of developers never have a need to know that nuance; it is useful context if you're dealing with boxing, though... and technically it isn't really C# knowledge, but rather: .NET knowledge (it would apply to all languages)
– Marc Gravell♦
Mar 27 at 8:31
5
@Sinatr you can't - the list never containsint?
- it only containsint
because of the boxing rules on nullable types
– Marc Gravell♦
Mar 27 at 8:34
1
@KyleJohnson you added a nullable int to the list. Naively, if nullable ints and ints are different things, you'd expect asking for all the ints in the list to return nothing. There are languages that do it that way, but C# has chosen to do it differently.
– mbrig
Mar 27 at 21:24
1
(and yes, my first sentence there is technically wrong. The nullable int never got added to the list. But if you don't know what's happening here, that's what it looks like is happening)
– mbrig
Mar 27 at 21:26
|
show 2 more comments
phew ok thank you for that explanaion. Is that C# basic knowledge?
– Dr. Snail
Mar 27 at 8:30
14
@Dr.Snail "basic" is relative / subjective, and I'd wager that a good percentage of developers never have a need to know that nuance; it is useful context if you're dealing with boxing, though... and technically it isn't really C# knowledge, but rather: .NET knowledge (it would apply to all languages)
– Marc Gravell♦
Mar 27 at 8:31
5
@Sinatr you can't - the list never containsint?
- it only containsint
because of the boxing rules on nullable types
– Marc Gravell♦
Mar 27 at 8:34
1
@KyleJohnson you added a nullable int to the list. Naively, if nullable ints and ints are different things, you'd expect asking for all the ints in the list to return nothing. There are languages that do it that way, but C# has chosen to do it differently.
– mbrig
Mar 27 at 21:24
1
(and yes, my first sentence there is technically wrong. The nullable int never got added to the list. But if you don't know what's happening here, that's what it looks like is happening)
– mbrig
Mar 27 at 21:26
phew ok thank you for that explanaion. Is that C# basic knowledge?
– Dr. Snail
Mar 27 at 8:30
phew ok thank you for that explanaion. Is that C# basic knowledge?
– Dr. Snail
Mar 27 at 8:30
14
14
@Dr.Snail "basic" is relative / subjective, and I'd wager that a good percentage of developers never have a need to know that nuance; it is useful context if you're dealing with boxing, though... and technically it isn't really C# knowledge, but rather: .NET knowledge (it would apply to all languages)
– Marc Gravell♦
Mar 27 at 8:31
@Dr.Snail "basic" is relative / subjective, and I'd wager that a good percentage of developers never have a need to know that nuance; it is useful context if you're dealing with boxing, though... and technically it isn't really C# knowledge, but rather: .NET knowledge (it would apply to all languages)
– Marc Gravell♦
Mar 27 at 8:31
5
5
@Sinatr you can't - the list never contains
int?
- it only contains int
because of the boxing rules on nullable types– Marc Gravell♦
Mar 27 at 8:34
@Sinatr you can't - the list never contains
int?
- it only contains int
because of the boxing rules on nullable types– Marc Gravell♦
Mar 27 at 8:34
1
1
@KyleJohnson you added a nullable int to the list. Naively, if nullable ints and ints are different things, you'd expect asking for all the ints in the list to return nothing. There are languages that do it that way, but C# has chosen to do it differently.
– mbrig
Mar 27 at 21:24
@KyleJohnson you added a nullable int to the list. Naively, if nullable ints and ints are different things, you'd expect asking for all the ints in the list to return nothing. There are languages that do it that way, but C# has chosen to do it differently.
– mbrig
Mar 27 at 21:24
1
1
(and yes, my first sentence there is technically wrong. The nullable int never got added to the list. But if you don't know what's happening here, that's what it looks like is happening)
– mbrig
Mar 27 at 21:26
(and yes, my first sentence there is technically wrong. The nullable int never got added to the list. But if you don't know what's happening here, that's what it looks like is happening)
– mbrig
Mar 27 at 21:26
|
show 2 more comments
A nullable value type is boxed by the following rules:
- If
HasValue
returnsfalse
, the null reference is produced. - If
HasValue
returnstrue
, a value of the underlying value typeT
is
boxed, not the instance of nullable.
In your example second rule has been followed as you have value, e.g. var i = (object)(int?)123;
add a comment |
A nullable value type is boxed by the following rules:
- If
HasValue
returnsfalse
, the null reference is produced. - If
HasValue
returnstrue
, a value of the underlying value typeT
is
boxed, not the instance of nullable.
In your example second rule has been followed as you have value, e.g. var i = (object)(int?)123;
add a comment |
A nullable value type is boxed by the following rules:
- If
HasValue
returnsfalse
, the null reference is produced. - If
HasValue
returnstrue
, a value of the underlying value typeT
is
boxed, not the instance of nullable.
In your example second rule has been followed as you have value, e.g. var i = (object)(int?)123;
A nullable value type is boxed by the following rules:
- If
HasValue
returnsfalse
, the null reference is produced. - If
HasValue
returnstrue
, a value of the underlying value typeT
is
boxed, not the instance of nullable.
In your example second rule has been followed as you have value, e.g. var i = (object)(int?)123;
edited Mar 27 at 13:26
answered Mar 27 at 9:11
JohnnyJohnny
3,8481021
3,8481021
add a comment |
add a comment |
It is a bit late, but beside of Marc's answer to your question, I want to give some additional information about Nullable value types in CLR.
The CLR has built-in support for nullable value types. This special support is provided for boxing, unboxing, calling GetType
, calling interface methods.
For example, let's check GetType()
:
Int32? x = 5;
Console.WriteLine(x.GetType());
What you think it will print to the console?System.Nullable<Int32
? Not, the result is System.Int32
.
Or, let's check boxing, which you noted in your question:
Int32? n =5;
Object o = n;
Console.WriteLine("o's type=0", o.GetType()); // "System.Int32"
The rule is that:
When the CLR is boxing a Nullable instance, it checks to see if it
is null, and if so, the CLR doesn’t actually box anything, and null is
returned. If the nullable instance is not null, the CLR takes the
value out of the nullable instance and boxes it. In other words, a
Nullable with a value of 5 is boxed into a boxed-Int32 with a
value of 5.
And, at the end I want to explain how CLR add special support for calling interface methods from Nullable Types.
Let's take a look to that:
Int32? n = 5;
Int32 result = ((IComparable) n).CompareTo(5); // Compiles & runs OK
Console.WriteLine(result); // 0
In the preceding code, I’m casting n, a Nullable<Int32>
, to IComparable<Int32>
, an interface
type. However, the Nullable<T>
type does not implement the IComparable<Int32>
interface asInt32
does. The C# compiler allows this code to compile anyway.
So, nullables have special treatment by the compiler? I couldn't implement these rules for my own type?
– Markonius
2 days ago
1
@Markonius For example you can not overrideGetType
for your own type to lie about the real type of your object. Because,GetType
is non-virtual.
– Farhad Jabiyev
2 days ago
add a comment |
It is a bit late, but beside of Marc's answer to your question, I want to give some additional information about Nullable value types in CLR.
The CLR has built-in support for nullable value types. This special support is provided for boxing, unboxing, calling GetType
, calling interface methods.
For example, let's check GetType()
:
Int32? x = 5;
Console.WriteLine(x.GetType());
What you think it will print to the console?System.Nullable<Int32
? Not, the result is System.Int32
.
Or, let's check boxing, which you noted in your question:
Int32? n =5;
Object o = n;
Console.WriteLine("o's type=0", o.GetType()); // "System.Int32"
The rule is that:
When the CLR is boxing a Nullable instance, it checks to see if it
is null, and if so, the CLR doesn’t actually box anything, and null is
returned. If the nullable instance is not null, the CLR takes the
value out of the nullable instance and boxes it. In other words, a
Nullable with a value of 5 is boxed into a boxed-Int32 with a
value of 5.
And, at the end I want to explain how CLR add special support for calling interface methods from Nullable Types.
Let's take a look to that:
Int32? n = 5;
Int32 result = ((IComparable) n).CompareTo(5); // Compiles & runs OK
Console.WriteLine(result); // 0
In the preceding code, I’m casting n, a Nullable<Int32>
, to IComparable<Int32>
, an interface
type. However, the Nullable<T>
type does not implement the IComparable<Int32>
interface asInt32
does. The C# compiler allows this code to compile anyway.
So, nullables have special treatment by the compiler? I couldn't implement these rules for my own type?
– Markonius
2 days ago
1
@Markonius For example you can not overrideGetType
for your own type to lie about the real type of your object. Because,GetType
is non-virtual.
– Farhad Jabiyev
2 days ago
add a comment |
It is a bit late, but beside of Marc's answer to your question, I want to give some additional information about Nullable value types in CLR.
The CLR has built-in support for nullable value types. This special support is provided for boxing, unboxing, calling GetType
, calling interface methods.
For example, let's check GetType()
:
Int32? x = 5;
Console.WriteLine(x.GetType());
What you think it will print to the console?System.Nullable<Int32
? Not, the result is System.Int32
.
Or, let's check boxing, which you noted in your question:
Int32? n =5;
Object o = n;
Console.WriteLine("o's type=0", o.GetType()); // "System.Int32"
The rule is that:
When the CLR is boxing a Nullable instance, it checks to see if it
is null, and if so, the CLR doesn’t actually box anything, and null is
returned. If the nullable instance is not null, the CLR takes the
value out of the nullable instance and boxes it. In other words, a
Nullable with a value of 5 is boxed into a boxed-Int32 with a
value of 5.
And, at the end I want to explain how CLR add special support for calling interface methods from Nullable Types.
Let's take a look to that:
Int32? n = 5;
Int32 result = ((IComparable) n).CompareTo(5); // Compiles & runs OK
Console.WriteLine(result); // 0
In the preceding code, I’m casting n, a Nullable<Int32>
, to IComparable<Int32>
, an interface
type. However, the Nullable<T>
type does not implement the IComparable<Int32>
interface asInt32
does. The C# compiler allows this code to compile anyway.
It is a bit late, but beside of Marc's answer to your question, I want to give some additional information about Nullable value types in CLR.
The CLR has built-in support for nullable value types. This special support is provided for boxing, unboxing, calling GetType
, calling interface methods.
For example, let's check GetType()
:
Int32? x = 5;
Console.WriteLine(x.GetType());
What you think it will print to the console?System.Nullable<Int32
? Not, the result is System.Int32
.
Or, let's check boxing, which you noted in your question:
Int32? n =5;
Object o = n;
Console.WriteLine("o's type=0", o.GetType()); // "System.Int32"
The rule is that:
When the CLR is boxing a Nullable instance, it checks to see if it
is null, and if so, the CLR doesn’t actually box anything, and null is
returned. If the nullable instance is not null, the CLR takes the
value out of the nullable instance and boxes it. In other words, a
Nullable with a value of 5 is boxed into a boxed-Int32 with a
value of 5.
And, at the end I want to explain how CLR add special support for calling interface methods from Nullable Types.
Let's take a look to that:
Int32? n = 5;
Int32 result = ((IComparable) n).CompareTo(5); // Compiles & runs OK
Console.WriteLine(result); // 0
In the preceding code, I’m casting n, a Nullable<Int32>
, to IComparable<Int32>
, an interface
type. However, the Nullable<T>
type does not implement the IComparable<Int32>
interface asInt32
does. The C# compiler allows this code to compile anyway.
edited Apr 2 at 21:53
answered Apr 2 at 17:59
Farhad JabiyevFarhad Jabiyev
19k64279
19k64279
So, nullables have special treatment by the compiler? I couldn't implement these rules for my own type?
– Markonius
2 days ago
1
@Markonius For example you can not overrideGetType
for your own type to lie about the real type of your object. Because,GetType
is non-virtual.
– Farhad Jabiyev
2 days ago
add a comment |
So, nullables have special treatment by the compiler? I couldn't implement these rules for my own type?
– Markonius
2 days ago
1
@Markonius For example you can not overrideGetType
for your own type to lie about the real type of your object. Because,GetType
is non-virtual.
– Farhad Jabiyev
2 days ago
So, nullables have special treatment by the compiler? I couldn't implement these rules for my own type?
– Markonius
2 days ago
So, nullables have special treatment by the compiler? I couldn't implement these rules for my own type?
– Markonius
2 days ago
1
1
@Markonius For example you can not override
GetType
for your own type to lie about the real type of your object. Because, GetType
is non-virtual.– Farhad Jabiyev
2 days ago
@Markonius For example you can not override
GetType
for your own type to lie about the real type of your object. Because, GetType
is non-virtual.– Farhad Jabiyev
2 days ago
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.
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%2f55372675%2ftype-int-vs-type-int%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
int?
boxed asint
, and basically every Nullable type, Edit : Marc Gravell have the full answer– styx
Mar 27 at 8:30
Related post about nullable type: stackoverflow.com/questions/4028830/…. This is called as "type lifting".
– Tetsuya Yamamoto
Mar 27 at 8:32
Before reading this topic I wouldn't even guess that even
List<int?>
already holds justint
types. Proof– Sinatr
Mar 27 at 8:46
7
@Sinatr no, that is incorrect;
List<int?>
holdsint?
. The important distinction in this example is the use ofList<object>
. What you're seeing in that "proof" is something very different;GetType()
on anyT?
either returns theT
, or throws a NRE. It never returnsT?
- better example: dotnetfiddle.net/3Gy3Fa - and as for why: becauseGetType()
is non-virtual, it cannot be overridden, and thus callingGetType()
is a boxing operation (even if used via "constrained call"). And when you box aT?
, you either get aT
as anobject
, or anull
.– Marc Gravell♦
Mar 27 at 8:49
@TetsuyaYamamoto That is not a relevant link. How is the boxing/unboxing behavior of Nullable<T> possible? is.
– GSerg
Mar 27 at 11:17