Reputation: 975
I have in my program defined an object log.
LoginModel log = new LoginModel ( ) ;
I do not write values into it. But why the object is not NULL when my function return it? (See picture)
[Bind(Exclude = "UserID")]
public class LoginModel
{
[ScaffoldColumn(false)]
public int UserID { get; set; }
[ScaffoldColumn(false)]
public string FirstName { get; set; }
[Display(Name = "E-mailadresse")]
[Required(ErrorMessage = "Skriv venligst din e-mailadresse", AllowEmptyStrings = false)]
[EmailAddress(ErrorMessage = "Ugyldig e-mailadresse")]
[DataType(DataType.EmailAddress)]
public string Emailaddress { get; set; }
[Display(Name = "Kodeord")]
[Required(ErrorMessage = "Skriv venligst et kodeord", AllowEmptyStrings = false)]
[DataType(DataType.Password)]
[StringLength(8, MinimumLength = 4, ErrorMessage = "Kodeordet skal mindst bestå af 4-8 karakter.")]
public string Password { get; set; }
}
Upvotes: 2
Views: 86
Reputation: 2305
https://en.wikipedia.org/wiki/Default_constructor
In both Java and C#, a "default constructor" refers to a nullary constructor that is automatically generated by the compiler if no constructors have been defined for the class. The default constructor implicitly calls the superclass's nullary constructor, then executes an empty body. All fields are left at their initial value of 0 (integer types), 0.0 (floating-point types), false (boolean type), or null (reference types). A programmer-defined constructor that takes no parameters is also called a default constructor in C#, but not in Java
And as everyone says, if you call the default constructor, the value of that object won't be null.
Upvotes: 1
Reputation: 11501
When you new an object it wont be null anymore.
if you have
LoginModel log;
or
LoginModel log =null;
Then it will be null. when you write
LoginModel log = new LoginModel ( ) ;
It will new your object and assign in to the variable (log),so it won't be null anymore. it will be the object with properties as you have initialized in your constructor (in your case there is no initialization, so every nullable property will be null and integers will be 0 , etc)
Upvotes: 1
Reputation: 29036
The code LoginModel log = new LoginModel ( ) ;
will create a new instance of the class LoginModel
which will contains all accessible properties and fields with default values. If you want log
to be null means declare like this:
LoginModel log;
Note : You should assign an instance of LoginModel
class to the log
to access values from it. Else it will throws NullReferenceException
Upvotes: 2