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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With