简体   繁体   中英

C# class ? in property (what does it mean?)

I'm studying for my MCPD and this example class is on shown in the ADO.net Entity Framework example. I haven't encounter? in the property such as OrderDate and EmployeeID Can someone please explain to me what it does or mean?

public class Order
{
 public int OrderID { get; set; }

 public string CustomerID { get; set; }
 public int? EmployeeID { get; set; }
 public DateTime? OrderDate { get; set; }
 public DateTime? RequiredDate { get; set; }
 public DateTime? ShippedDate { get; set; }
 public int? ShipVia { get; set; }
 public decimal? Freight { get; set; }
 public string ShipName { get; set; }
 public string ShipAddress { get; set; }
 public string ShipCity { get; set; }
 public string ShipRegion { get; set; }
 public string ShipPostalCode { get; set; }
 public string ShipCountry { get; set; }
 public Customer Customer { get; set; }
}

It's short for the type Nullable<T> where T is the type that precedes the ? . Thus

public int? EmployeeID { get; set; }

is equivalent to

public Nullable<int> EmployeeID { get; set; }

Effectively, a nullable type allows you to assign null to value types. These types are very special as various operators and methods on the corresponding non-nullable type are "lifted" to the nullable type.

Note that T must be a non-nullable value type. Also, it's a common misconception that Nullable<T> is a reference type. It is a value type, albeit a rather special one (it gets help from the compiler to be so special). For example, boxing and unboxing operations are treated very specially (the underlying value is boxed, unless it is null in which case the boxed instance of object is the null reference; if null is unboxed to an instance of a nullable type, it is unboxed to the value where HasValue is false ).

It means its nullable. A nullable value can contain a value or it can be null, like this:

int? myVar = 4;

myVar = null //myVar is now null. This would be illegal is myVar wasn't nullable

myVar = 17 // myVar now contains 17

It means the variable is nullable.

[ValueType]? is shorthand for the Nullable class.

It will accept a null assignment (which value types can't). When you're ready to access the value, you can check myNullable == null or myNullable.HasValue and the actual valueType (int, DateTime, whatever) will be in myNullable.Value .

It just makes the value nullable. Which means you can assign "null" to the property. Without the "?" You wouldn't be able to.

nullable, when you use the database, you can set column as int null so in the c# int is not null,because int is the value type. so in c# support the int?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM