When to use NEW keyword in C# when creating an object in ASP.NET MVC 5

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