c# "?" in method declaration - c#

I'm learning C# at the moment, and I have never seen this before.
static int? Foo()
{
return Bar
}
What does the "?" do?
I did try looking it up on Google and SE but I don't really know what key terms I should be searching for.

The int? is a nullable int. Using this as the return type of your method means that this method returns either an int or null. According to MSDN
Nullable types are instances of the System.Nullable struct. A
nullable type can represent the correct range of values for its
underlying value type, plus an additional null value. For example, a
Nullable, pronounced "Nullable of Int32," can be assigned any
value from -2147483648 to 2147483647, or it can be assigned the null
value.

int? = the value can be integer or null

int? is a type and is equivalent to Nullable<int>.
This type can store an Integer or Null.

int? is the shorthand for Nullable<int> More info here: Nullable ᐸTᐳ Structure
It allows you to have "null" values in your int. More info here: Using Nullable Types

This is a syntactic shortcut to define a nullable type, which is usually defined using the type Nullable<T>

Related

Overloading the = operator for nullable types?

The MSDN mentions that overloading the = operator is not possible.
How is it possible then for Nullable types to be assigned to null?
int? i = null;
Besides can I do it with my own generic types and how?
It's the implicit-conversion not the assignment-operator that allows to assign null: http://msdn.microsoft.com/en-us/library/ms131346(v=vs.110).aspx
If the value parameter is not null, the Value property of the new
Nullable<T> value is initialized to the value parameter and the
HasValue property is initialized to true. If the value parameter is
null, the Value property of the new Nullable<T> value is initialized
to the default value, which is the value that is all binary zeroes,
and the HasValue property is initialized to false.
Essentially what Tim's comment (Edit: And now answer =D) says - There's an implicit conversion from the null literal, rather than an overload of the assignment operator.
From the C# language spec (I was looking at Version 5.0) - Section "6.1.5 Null literal conversions":
An implicit conversion exists from the null literal to any nullable
type. This conversion produces the null value (§4.1.10) of the given
nullable type.
There is special compiler support for the Nullable type.
It is impossible to create a user-defined implicit conversion to/from null. They built it into the language (and the runtime) rather than creating Nullable on top of the language, as so many BCL classes are made.
Interestingly this is not the only special support created for Nullable. When you box a Nullable<T> it doesn't actually box a Nullable object, ever. If HasValue is false, null is boxed, and if it's true, the underlying value is unwrapped and boxed. It would be impossible to do this for your own type.
Nullable types are instances of the struct
System.Nullable<T>.
The type that can be specified or made nullable is specified as the generic type of nullable (T).
More info here...http://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx
In your example, you're not actually setting an int to null, rather setting the value on the struct which encapsulates it to null.

C# syntax questions [duplicate]

This question already has answers here:
What is the purpose of a question mark after a value type (for example: int? myVariable)?
(9 answers)
Closed 9 years ago.
i have seen the following code in an c# example:
public void AddScreen(GameScreen screen, PlayerIndex? controllingPlayer)
{
screen.ControllingPlayer = controllingPlayer;
screen.ScreenManager = this;
screen.IsExiting = false;
}
and i have no clue what the ? is doing after PlayerIndex, it is an enum, and in the class every notice of it is with the ? behind it.
my question: what does it do, what is it called and why would you use it.
I have googled this, but it didn't get me far since i dont know the name of this coding and google filters out the question mark in the search query
The ? makes PlayerIndex a NULLABLE type.
That way controllingPlayer can be NULL even if it is an enum or a basic type like int.
The ? is a nullable type. This means that controllingPlayer can contain null or a value.
To check whether there is a value associated with the variable, you can use HasValue. To retrieve the actual value, use Value
if ( controllingPlayer.HasValue )
// now do something with controllingPlayer.Value
The question mark denotes that PlayerIndex is treated as a nullable type.
Probably PlayerIndex is not a class or struct but an enum or alias for int or something like that. If it's an alias, you should find something like this in the code:
using PlayerIndex= System.Int32;
It's short for Nullable<PlayerIndex> which means that you can pass a PlayerIndex value or null.
The ? is indicating that controllingPlayer can be null. It could also be written as Nullable<PlayerIndex> controllerPlayer.
This is useful when working with valuetypes which can not be null, like reference types can be. If you have a regular int, you cannot differentiate between a variable that is given the value 0 and a variable that is never written to. By wrapping it in a Nullable<>, you can now check if it has a value or not:
int notNullable; //will be initialized to 0 by default.
int? nullable; //will be initialized to null by default.
if (nullable.HasValue) //Do something if the variable has been given a value
{
return nullable.Value; //get the actual int-value
}
See msdn documentation for nullable types: http://msdn.microsoft.com/en-us/library/1t3y8s4s(v=vs.80).aspx
It means that the value type in question is a nullable type
Appending ? to a type when defining something it is shorthand for wrapping in a Nullable<T> (see Nullable Types for further details). This means that value types, usually not able to express nullity, can be checked for a non-value instead of always resorting to their default (i.e., an int, rather than default to 0, will default to null).
You may check whether or not the thing has a value, and access the value thusly:
var hasValue = nullableThing.HasValue;
var underlyingValue = nullableThing.Value;
PlayerIndex? indicate that varible can be null value. The syntax T? is shorthand for System.Nullable, where T is a value type. please refer to Nullable Types (C# Programming Guide).

C# syntax question [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
? (nullable) operator in C#
What does the ? do used like this:
class Test
{
public int? aux;
}
It's probably a simple question for someone more familiar with c#, but I don't really know what to search for. I read an explanation but didn't fully understand it. I would also be interested in knowing what the "??" operator does. Some examples on where they would be useful would be of great help.
This (int?) is shorthand for Nullable<int>.
It can be any int value plus an additional null. See more info Nullable Types
The purpose of using Nullable int is while often using database operations, there are conditions where some value might be null and we have to express in code. For Example consider the folowing schema
Employee
- id, bigint, not null
- name, nvarchar(100), null
- locationId, bigint, null
Suppose locationId of an employee is not available, so in database the value of locationid of employee is NULL. On C# side, you know that int can not have a NULL value, so type, Nullable int(and few others) has been added, due to which we can easily show that locationId has no value.
"?" denotes a nullable type
int? means nullable integer: aux can have an int value or be null!!
As many others have already answered, the ? denotes nullable types. This means that a variable of type int? can be assigned null in addition to an integer values.
This is used when you want to distinguish the case of a variable which has not been initialized from the case in which it has been assigned the default value.
For instance you can consider the case of bool. When you declare a bool variable, it has the false value by default. This means that when its value is false you can't tell if this happens because someone has assigned the variable that value, of because nobody touched it. In this case a bool? is useful since it allows you to distinguish a "real" false value (explicitely assigned by some code) from the not initailized case.

Why int can't be null? How does nullable int (int?) work in C#?

I am new to C# and just learned that objects can be null in C# but int can't.
Also how does nullable int (int?) work in C#?
int is a primitive type and only ReferenceTypes (objects) are nullable. You can make an int nullable by wrapping it in an object:
System.Nullable<int> i;
-or-
int? i;
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/nullable-types/using-nullable-types
An int is a value type. It is really of type Int32. Objects that can be nullable are reference types. At a basic level the difference is that a value type will store the value with the variable where a reference type will store a reference to the value. A reference can be null, meaning that it doesn't point to a value. Where a value type always has a value.
Nullable wraps a value type to allow you to have the option of being null. Using int? is just a compiler shortcut to declare a nullable type.
You can have a nullable int by using int? or Nullable<int> both are exactly the same thing.
Value types like int contain direct values rather than references like ReferenceType. A value cannot be null but a reference can be null which means it is pointing to nothing. A value cannot have nothing in it. A value always contain some kind of value
Nullable or Nullable types are special value types which in addition to normal values of value types also support additional null value just like reference types
Objects are reference types and they can reference nothing or NULL, however int is a value type, which can only hold a value, and cannot reference anything.
Primitive int type cannot express null in its binary representation, but Nullable<int> added an extra byte to express the null information of this value.

Explanation of int? vs int [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What's the difference between 'int?' and 'int' in C#?
I've come across some code in C# that declares a variable as: int? number
What does the ? mean and how does this differ from just: int
int cannot be null.
int? is an alias for the Nullable<int> struct, which you can set to null.
int? is a shorthand for creating an instance of the generic System.Nullable<T> structure type. It allows you to make your variable nullable. Remember, given that the <ValueType>? syntax is a shorthand, you could declare your variables thus:
Nullable<int> i = 10;
int? is shorthand for Nullable<int> which allows you to pretend that an integer can handle nulls.
int? foo = null;
It is useful for indicating a lack of value where you would previously have used a magic value (-1) in the past, and also useful when dealing with database columns that allow null entries.
For a quasi-in-depth look, a Nullable<T> (introduced in .NET 2.0) is simply a wrapper over a value type T that exposes two properties, HasValue and Value, where HasValue is a boolean that indicates if the value has been set and Value (obviously enough) returns the value. It is an error to access Value if HasValue is false. Therefore, to access Value, it is good form to check HasValue first. Additionally, if you simply want to normalize any non-values to default values (0 for numeric types), you can use the method GetValueOrDefault() without needing to check HasValue.
Note that although you appear to set foo to null, it's not actually null under normal usage scenarios. null is simply additional syntactic sugar for this type. The above line of code translates to
Nullable<int> foo = new Nullable<int>();
Initializing the variable in this fashion simply sets the HasValue property to false.
However, in situations involving boxing, the value will actually box to null if HasValue is false (it will otherwise box to T). Be aware of the consequences! For example, in:
int? foo = null;
string bar = foo.ToString(); // this is fine, returns string.Empty
Type type = foo.GetType(); // blows up! GetType causes the value to box
// resulting in a NullReferenceException
That's a quick crash course. For more, visit the documentation.
It's syntactic compiler sugar for Nullable<int>
Basically your number (or any other value type) can be null as well as it's value. You check for a value using the HasValue property. They can be cast into their value types (although this will fail if they're null) or you can use the Value property (again it will throw an exception if it is null)
One thing which usually appears to be overlooked when using nullable types is the GetValueOrDefault() method which returns default(T) if the object is null.
As #Kyle Trauberman points out in the comment you can indeed compare it to null instead of checking HasValue. The type itself is a value type with overriden equality methods so that much as it will never be null itself it will return true when compared to null if it doesn't have a value.
A questionmark behind the declaration means that the variable is nullable.
int? can be null where as int can not.
Reference Nullable Types:
http://msdn.microsoft.com/en-us/library/1t3y8s4s(v=VS.100).aspx

Categories

Resources