Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between the keywords default and new

Tags:

c#

below is a sample class,

public class Loan
{
}

now, what is difference between these below 2 line and what is difference between them?

Loan loan = default(Loan);
Loan loan = new Loan();

Is there preference to use one over other?

like image 571
user2994834 Avatar asked Jun 17 '14 17:06

user2994834


1 Answers

default is used for zeroing out values. For reference types, thats null. For value types, that is effectively the same as using new without any arguments. default is great for generics.

new creates an instance of that type, invoking the constructor.

In your example, if I do:

Loan loan = default(Loan);

or in newer versions of C#:

Loan loan = default;

which is logically equivalent to

Loan loan = null;

you will get a null reference exception if you don't construct it:

loan.MakePayment(100); // Throws
like image 125
Daniel A. White Avatar answered Oct 14 '22 07:10

Daniel A. White