In ISerialized, Resharper is complaining that "Only implementations of 'SerializeShape" are used. Is there something more I should be doing, or is my use of an interface simply over-kill in this instance? My 'requirements' are that any use of class Shape implement SerializeShape. I am attempting to use Interface in a plausible, conventional way, but maybe I am not?
I have an interface of such:
namespace Shapes
{
internal interface ISerialized<in T>
{
string SerializeShape();
}
}
I have a class of such:
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace Shapes
{
[DataContract]
public class Shape : ISerialized<Shape>
{
[DataMember] public double Perimeter { get; set; }
[DataMember] public double Area { get; set; }
[DataMember] public string ShapeName { get; set; }
[DataMember] public string ShapeException { get; set; }
public string SerializeShape(Shape shape)
{
return JsonConvert.SerializeObject(shape, Formatting.Indented);
}
}
}
An Interface is a collection of loosely bound items that have a common functionality or attributes. Interfaces contain method signatures, properties, events etc. Interfaces are used so that one class or struct can implement multiple behaviors.
Declare the missing methods abstract in your class. This forces you to declare your class abstract and, as a result, forces you to subclass the class (and implement the missing methods) before you can create any objects.
Yes, it is mandatory to implement all the methods in a class that implements an interface until and unless that class is declared as an abstract class.
Press Ctrl+F12 or choose Navigate | Implementation(s) from the main menu . Alternatively, you can press Ctrl+Shift+A , start typing the command name in the popup, and then choose it there.
In essence if all you do is have a class implement an interface, then there is no use for the interface. It must be referenced inlieu of the class to be of any real benefit. A brief contrived example to explain in code:
public interface IFoo
{
string Bar();
}
public class Foo : IFoo
{
public string Bar()
{
return "Foo";
}
}
public class FooTwo : IFoo
{
public string Bar()
{
Return "FooTwo";
}
}
public class FooBar
{
public void UseFoo()
{
IFoo foo = new Foo();
string result = foo.Bar();
}
public void UseFooTwo()
{
IFoo fooTwo = new FooTwo()
string result = fooTwo.Bar();
}
}
As you can see both methods in FooBar
use IFoo
instead of the actual implementation of Foo
or FooTwo
. This allows you (or someone who is implementing a portion of code you wrote) to honor the contract that is IFoo
. If they had done FooTwo fooTwo = new FooTwo()
then they aren't really getting any benefit of FooTwo
implementing IFoo
.
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