I am a beginner and learning web development using ASP.Net MVC 5 framework in C# language. I came across below code:
Scenario 1: No New
Keyword used in Object Creation.
[AuthorizeFunc]
[BlockWidget]
public PartialViewResult WidgetPayments()
{
PaymentFormMV data; // No New Keyword used
if (SimUtils.IsDelayedPaymentAllowed)
{
data = Pay.GetData(PaymentPageMode.DelayedPayment);
}
else
{
data = PayHelp.GetData(PaymentPageMode.MakePayment);
}
return PartialView("PaymentsWrapper", data);
}
Scenario 2: New
Keyword used in Object Creation.
[AuthorizeFunc]
[BlockWidget]
public PartialViewResult WidgetPayments()
{
PaymentFormMV data = new PaymentFormMV(); // New Keyword used
if (SimUtils.IsDelayedPaymentAllowed)
{
data = Pay.GetData(PaymentPageMode.DelayedPayment);
}
else
{
data = PayHelp.GetData(PaymentPageMode.MakePayment);
}
return PartialView("PaymentsWrapper", data);
}
I am a beginner and I tried both code, and both code snippets work fine for me.
new
and when not to use new
. Can some one tell me one example for both scenario?Can some one please guide me a little?
Look at more than just that one line, look at what the rest of that method is doing. In all logical cases, (if
and else
), that variable is set to something. (Assuming that the .GetData()
methods successfully return something.)
In a general sense, you use new
when you want to create a new instance of an object. The example you show doesn't need to do that, because the very next thing it does is replace that instance with another instance. There's no need to create something just to immediately throw it away.
Why both code works fine? What is the difference between both of them?
The simplest way of putting it would be "because they do the same thing". More specifically, your second code snippet makes an assignment that is ignored; other than that one assignment, the code is identical.
When to use "new" and when not to use
When all branches of code make an assignment, as in your case, do not use new
. When you need to assign an object, and then re-assign it later on, use new
. If you do not need an object in some cases, but do need it in others, use null
instead of new
.
Note that if you leave a local variable unassigned, the compiler will check if all branches do the assignment for you before the first read of the variable:
PaymentFormMV data;
if (SimUtils.IsDelayedPaymentAllowed)
{
data = Pay.GetData(PaymentPageMode.DelayedPayment);
} // No "else"
return PartialView("PaymentsWrapper", data); // Compile-time error
In both cases you are creating a new instance of the object within your if statement so whether it is contructed and assigned an instance originally is irrelevant as it is replaced.
If you were to query the object immediately after declaration in the first instance you would see it is null, whereas in the second instance it would be a PaymentsFormMV.
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