Difference between "var objectName= new SomeObject()" and "interfaceName objectName= new SomeObject()"

StackOverflow https://stackoverflow.com/questions/15681665

Вопрос

I was doing some code analysis via code inspections from resharper and i got the next warning:

Only implementations of property 'propertyname' are used

This warning i have on my interface, if I google i found this page of jetbrains: http://confluence.jetbrains.com/display/ReSharper/Only+implementations+of+property+are+used

That didn't helped me at all because then i wouldn't have an interface anymore...

So I started testing how to get rid of that warning. On the folowing dummy interface and class:

public interface ITest
{
    string Name { get; set; }
}

public class Test: ITest
{
    public string Name { get; set; }
}

if i use:

var newTest = new Test();
newTest.Name= "newName";

Then the warning occurs. But when I use the next line, the warning will disappear.

ITest newTest = new Test();
newTest.Name = "newName";

I'm not an interface Ninja, so i was wondering, what is the difference between both manners..?

Thanks!

Это было полезно?

Решение

This infers the concrete type:

//X is of type X
var x = new X(); 

This does not

//X is of type IX
IX x = new X();

I'm guessing the warning will still occurt if you write

//X is of type X
X x = new X();

Also does the following remove the warning?

public void TestX()
{
    //X is of type X
    var x = new X();
    UseIX(x);
}

public void UseIX(IX interfaceParam)
{
    interfaceParam.Foo = 1;
}

Другие советы

var newTest = new Test() will set the type of newTest to Test. ITest newTest = new Test() will set the type of newTest to ITest.

So with the former ITest is not required as it is never used.

So resharper is just saying you don't need ITest. It's up to you whether you agree. Do you need ITest?

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top