How do you extend Classes and Structs with Interfaces via extension in C#?











up vote
0
down vote

favorite












I am making a utility library for various .Net Framework datastructures in C#. I am trying to add ICloneable to Dictionary<>. Is there a way to do this through an extension, like how you make extension methods?



To clarify further, in C# you can extend from already existing classes by making "Extension Methods" in a static class, like so:



public static class MyExtensions
{
public static void MyArrayExtension<T>(this T arg)
{
//Your code here...
}
}


This allows you to do the function on all arrays, like so:



MyArray.MyArrayExtension();


You can create extension methods to extend all classes and structs, including those that you reference in DLLs like those for the .Net Framework. I am using this currently to help me design a utility library, with tons of useful extensions that I feel should have been implemented in C# in the first place.



When looking at System.Linq, it appears that Interfaces are somehow added to certain datastructure classes like Array and List<>, but only when the namespace is included. I am trying to figure out how this is done, as I cannot find any examples after searching online.










share|improve this question




















  • 1




    You can add a .Clone extension method but you cannot tuck on a whole interface, that is not possible. Unless you modify the class declaration, it will never implement ICloneable. What you're asking for is similar to what is called "shapes", where a class that implements all the necessary bits can be said to have "the shape of Y", which could be similar to an interface. You can read more about shapes here.
    – Lasse Vågsæther Karlsen
    Nov 8 at 14:56












  • Make that an answer then, and I will mark it as the answer.
    – Lockethot
    Nov 8 at 14:57















up vote
0
down vote

favorite












I am making a utility library for various .Net Framework datastructures in C#. I am trying to add ICloneable to Dictionary<>. Is there a way to do this through an extension, like how you make extension methods?



To clarify further, in C# you can extend from already existing classes by making "Extension Methods" in a static class, like so:



public static class MyExtensions
{
public static void MyArrayExtension<T>(this T arg)
{
//Your code here...
}
}


This allows you to do the function on all arrays, like so:



MyArray.MyArrayExtension();


You can create extension methods to extend all classes and structs, including those that you reference in DLLs like those for the .Net Framework. I am using this currently to help me design a utility library, with tons of useful extensions that I feel should have been implemented in C# in the first place.



When looking at System.Linq, it appears that Interfaces are somehow added to certain datastructure classes like Array and List<>, but only when the namespace is included. I am trying to figure out how this is done, as I cannot find any examples after searching online.










share|improve this question




















  • 1




    You can add a .Clone extension method but you cannot tuck on a whole interface, that is not possible. Unless you modify the class declaration, it will never implement ICloneable. What you're asking for is similar to what is called "shapes", where a class that implements all the necessary bits can be said to have "the shape of Y", which could be similar to an interface. You can read more about shapes here.
    – Lasse Vågsæther Karlsen
    Nov 8 at 14:56












  • Make that an answer then, and I will mark it as the answer.
    – Lockethot
    Nov 8 at 14:57













up vote
0
down vote

favorite









up vote
0
down vote

favorite











I am making a utility library for various .Net Framework datastructures in C#. I am trying to add ICloneable to Dictionary<>. Is there a way to do this through an extension, like how you make extension methods?



To clarify further, in C# you can extend from already existing classes by making "Extension Methods" in a static class, like so:



public static class MyExtensions
{
public static void MyArrayExtension<T>(this T arg)
{
//Your code here...
}
}


This allows you to do the function on all arrays, like so:



MyArray.MyArrayExtension();


You can create extension methods to extend all classes and structs, including those that you reference in DLLs like those for the .Net Framework. I am using this currently to help me design a utility library, with tons of useful extensions that I feel should have been implemented in C# in the first place.



When looking at System.Linq, it appears that Interfaces are somehow added to certain datastructure classes like Array and List<>, but only when the namespace is included. I am trying to figure out how this is done, as I cannot find any examples after searching online.










share|improve this question















I am making a utility library for various .Net Framework datastructures in C#. I am trying to add ICloneable to Dictionary<>. Is there a way to do this through an extension, like how you make extension methods?



To clarify further, in C# you can extend from already existing classes by making "Extension Methods" in a static class, like so:



public static class MyExtensions
{
public static void MyArrayExtension<T>(this T arg)
{
//Your code here...
}
}


This allows you to do the function on all arrays, like so:



MyArray.MyArrayExtension();


You can create extension methods to extend all classes and structs, including those that you reference in DLLs like those for the .Net Framework. I am using this currently to help me design a utility library, with tons of useful extensions that I feel should have been implemented in C# in the first place.



When looking at System.Linq, it appears that Interfaces are somehow added to certain datastructure classes like Array and List<>, but only when the namespace is included. I am trying to figure out how this is done, as I cannot find any examples after searching online.







c# interface extension-methods






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 8 at 15:13

























asked Nov 8 at 14:05









Lockethot

612




612








  • 1




    You can add a .Clone extension method but you cannot tuck on a whole interface, that is not possible. Unless you modify the class declaration, it will never implement ICloneable. What you're asking for is similar to what is called "shapes", where a class that implements all the necessary bits can be said to have "the shape of Y", which could be similar to an interface. You can read more about shapes here.
    – Lasse Vågsæther Karlsen
    Nov 8 at 14:56












  • Make that an answer then, and I will mark it as the answer.
    – Lockethot
    Nov 8 at 14:57














  • 1




    You can add a .Clone extension method but you cannot tuck on a whole interface, that is not possible. Unless you modify the class declaration, it will never implement ICloneable. What you're asking for is similar to what is called "shapes", where a class that implements all the necessary bits can be said to have "the shape of Y", which could be similar to an interface. You can read more about shapes here.
    – Lasse Vågsæther Karlsen
    Nov 8 at 14:56












  • Make that an answer then, and I will mark it as the answer.
    – Lockethot
    Nov 8 at 14:57








1




1




You can add a .Clone extension method but you cannot tuck on a whole interface, that is not possible. Unless you modify the class declaration, it will never implement ICloneable. What you're asking for is similar to what is called "shapes", where a class that implements all the necessary bits can be said to have "the shape of Y", which could be similar to an interface. You can read more about shapes here.
– Lasse Vågsæther Karlsen
Nov 8 at 14:56






You can add a .Clone extension method but you cannot tuck on a whole interface, that is not possible. Unless you modify the class declaration, it will never implement ICloneable. What you're asking for is similar to what is called "shapes", where a class that implements all the necessary bits can be said to have "the shape of Y", which could be similar to an interface. You can read more about shapes here.
– Lasse Vågsæther Karlsen
Nov 8 at 14:56














Make that an answer then, and I will mark it as the answer.
– Lockethot
Nov 8 at 14:57




Make that an answer then, and I will mark it as the answer.
– Lockethot
Nov 8 at 14:57












1 Answer
1






active

oldest

votes

















up vote
2
down vote



accepted










As of now, this is not possible.



You can add the requisite Clone extension methods, but there is no way right now to tuck on a whole interface.



Remember that checking for support for an interface could be written in existing code like this:



if (dictionary is ICloneable cloneable)
var clone = cloneable.Clone();


But this would not work with just extension something as the underlying type does not in fact implement the interface.





There are some ongoing efforts in this line of thought:




  • Extension everything

  • Shapes


I have no idea how good they manage to get these things so whether it could potentially solve this in the future is a bit up in the air.





Note that you could do this using decoration, but it might be a bit of work and it would require you to construct your dictionaries using a different type:



public class CloneableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, ICloneable
{
... methods and properties that delegate to base.XYZ

public object Clone() => new ...
}


Everywhere you construct your object you would then have to write this:



var dictionary = new CloneableDictionary<...>();


instead of:



var dictionary = new Dictionary<...>();


Since CloneableDictionary inherits Dictionary, you could drop it into variables and parameters that already exists, even if their type is kept as Dictionary<...>, but if you forget that you're really storing other dictionary types in there and construct new, normal, non-cloneable, dictionaries some places it may quickly fall down.






share|improve this answer























  • I appreciate the answer, though it is upsetting that I cannot achieve the desired result. The example you show with code is exactly the problem I'm worried about. The Prototype Pattern requires the interface to be implemented, and making the Dictionary class not be ICloneable will make things much more complicated for users down the line.
    – Lockethot
    Nov 8 at 15:04










  • Note that ICloneable is a horrible interface and should not be used. Almost every time someone uses this interface they expect it to behave different than what it does because peoples expectations to cloning things do not align. For instance, do you expect it to just clone the dictionary, or should the cloned dictionary also contain cloned keys and cloned values? What about objects referred to from these cloned values, should they be cloned as well? You're almost always better off writing your own clone method exactly like you expect it to be.
    – Lasse Vågsæther Karlsen
    Nov 8 at 15:04










  • I posted the above comment as a comment because this is my opinion, and should be seen in a different light compared to my answer which is more listing why you cannot do it and existing efforts in this kind of thing.
    – Lasse Vågsæther Karlsen
    Nov 8 at 15:06










  • I think I may do the ICloneable dictionary suggestion you just added. Seems to be the best solution to this problem.
    – Lockethot
    Nov 8 at 15:07











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53209390%2fhow-do-you-extend-classes-and-structs-with-interfaces-via-extension-in-c%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
2
down vote



accepted










As of now, this is not possible.



You can add the requisite Clone extension methods, but there is no way right now to tuck on a whole interface.



Remember that checking for support for an interface could be written in existing code like this:



if (dictionary is ICloneable cloneable)
var clone = cloneable.Clone();


But this would not work with just extension something as the underlying type does not in fact implement the interface.





There are some ongoing efforts in this line of thought:




  • Extension everything

  • Shapes


I have no idea how good they manage to get these things so whether it could potentially solve this in the future is a bit up in the air.





Note that you could do this using decoration, but it might be a bit of work and it would require you to construct your dictionaries using a different type:



public class CloneableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, ICloneable
{
... methods and properties that delegate to base.XYZ

public object Clone() => new ...
}


Everywhere you construct your object you would then have to write this:



var dictionary = new CloneableDictionary<...>();


instead of:



var dictionary = new Dictionary<...>();


Since CloneableDictionary inherits Dictionary, you could drop it into variables and parameters that already exists, even if their type is kept as Dictionary<...>, but if you forget that you're really storing other dictionary types in there and construct new, normal, non-cloneable, dictionaries some places it may quickly fall down.






share|improve this answer























  • I appreciate the answer, though it is upsetting that I cannot achieve the desired result. The example you show with code is exactly the problem I'm worried about. The Prototype Pattern requires the interface to be implemented, and making the Dictionary class not be ICloneable will make things much more complicated for users down the line.
    – Lockethot
    Nov 8 at 15:04










  • Note that ICloneable is a horrible interface and should not be used. Almost every time someone uses this interface they expect it to behave different than what it does because peoples expectations to cloning things do not align. For instance, do you expect it to just clone the dictionary, or should the cloned dictionary also contain cloned keys and cloned values? What about objects referred to from these cloned values, should they be cloned as well? You're almost always better off writing your own clone method exactly like you expect it to be.
    – Lasse Vågsæther Karlsen
    Nov 8 at 15:04










  • I posted the above comment as a comment because this is my opinion, and should be seen in a different light compared to my answer which is more listing why you cannot do it and existing efforts in this kind of thing.
    – Lasse Vågsæther Karlsen
    Nov 8 at 15:06










  • I think I may do the ICloneable dictionary suggestion you just added. Seems to be the best solution to this problem.
    – Lockethot
    Nov 8 at 15:07















up vote
2
down vote



accepted










As of now, this is not possible.



You can add the requisite Clone extension methods, but there is no way right now to tuck on a whole interface.



Remember that checking for support for an interface could be written in existing code like this:



if (dictionary is ICloneable cloneable)
var clone = cloneable.Clone();


But this would not work with just extension something as the underlying type does not in fact implement the interface.





There are some ongoing efforts in this line of thought:




  • Extension everything

  • Shapes


I have no idea how good they manage to get these things so whether it could potentially solve this in the future is a bit up in the air.





Note that you could do this using decoration, but it might be a bit of work and it would require you to construct your dictionaries using a different type:



public class CloneableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, ICloneable
{
... methods and properties that delegate to base.XYZ

public object Clone() => new ...
}


Everywhere you construct your object you would then have to write this:



var dictionary = new CloneableDictionary<...>();


instead of:



var dictionary = new Dictionary<...>();


Since CloneableDictionary inherits Dictionary, you could drop it into variables and parameters that already exists, even if their type is kept as Dictionary<...>, but if you forget that you're really storing other dictionary types in there and construct new, normal, non-cloneable, dictionaries some places it may quickly fall down.






share|improve this answer























  • I appreciate the answer, though it is upsetting that I cannot achieve the desired result. The example you show with code is exactly the problem I'm worried about. The Prototype Pattern requires the interface to be implemented, and making the Dictionary class not be ICloneable will make things much more complicated for users down the line.
    – Lockethot
    Nov 8 at 15:04










  • Note that ICloneable is a horrible interface and should not be used. Almost every time someone uses this interface they expect it to behave different than what it does because peoples expectations to cloning things do not align. For instance, do you expect it to just clone the dictionary, or should the cloned dictionary also contain cloned keys and cloned values? What about objects referred to from these cloned values, should they be cloned as well? You're almost always better off writing your own clone method exactly like you expect it to be.
    – Lasse Vågsæther Karlsen
    Nov 8 at 15:04










  • I posted the above comment as a comment because this is my opinion, and should be seen in a different light compared to my answer which is more listing why you cannot do it and existing efforts in this kind of thing.
    – Lasse Vågsæther Karlsen
    Nov 8 at 15:06










  • I think I may do the ICloneable dictionary suggestion you just added. Seems to be the best solution to this problem.
    – Lockethot
    Nov 8 at 15:07













up vote
2
down vote



accepted







up vote
2
down vote



accepted






As of now, this is not possible.



You can add the requisite Clone extension methods, but there is no way right now to tuck on a whole interface.



Remember that checking for support for an interface could be written in existing code like this:



if (dictionary is ICloneable cloneable)
var clone = cloneable.Clone();


But this would not work with just extension something as the underlying type does not in fact implement the interface.





There are some ongoing efforts in this line of thought:




  • Extension everything

  • Shapes


I have no idea how good they manage to get these things so whether it could potentially solve this in the future is a bit up in the air.





Note that you could do this using decoration, but it might be a bit of work and it would require you to construct your dictionaries using a different type:



public class CloneableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, ICloneable
{
... methods and properties that delegate to base.XYZ

public object Clone() => new ...
}


Everywhere you construct your object you would then have to write this:



var dictionary = new CloneableDictionary<...>();


instead of:



var dictionary = new Dictionary<...>();


Since CloneableDictionary inherits Dictionary, you could drop it into variables and parameters that already exists, even if their type is kept as Dictionary<...>, but if you forget that you're really storing other dictionary types in there and construct new, normal, non-cloneable, dictionaries some places it may quickly fall down.






share|improve this answer














As of now, this is not possible.



You can add the requisite Clone extension methods, but there is no way right now to tuck on a whole interface.



Remember that checking for support for an interface could be written in existing code like this:



if (dictionary is ICloneable cloneable)
var clone = cloneable.Clone();


But this would not work with just extension something as the underlying type does not in fact implement the interface.





There are some ongoing efforts in this line of thought:




  • Extension everything

  • Shapes


I have no idea how good they manage to get these things so whether it could potentially solve this in the future is a bit up in the air.





Note that you could do this using decoration, but it might be a bit of work and it would require you to construct your dictionaries using a different type:



public class CloneableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, ICloneable
{
... methods and properties that delegate to base.XYZ

public object Clone() => new ...
}


Everywhere you construct your object you would then have to write this:



var dictionary = new CloneableDictionary<...>();


instead of:



var dictionary = new Dictionary<...>();


Since CloneableDictionary inherits Dictionary, you could drop it into variables and parameters that already exists, even if their type is kept as Dictionary<...>, but if you forget that you're really storing other dictionary types in there and construct new, normal, non-cloneable, dictionaries some places it may quickly fall down.







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 8 at 15:08

























answered Nov 8 at 14:59









Lasse Vågsæther Karlsen

285k82518715




285k82518715












  • I appreciate the answer, though it is upsetting that I cannot achieve the desired result. The example you show with code is exactly the problem I'm worried about. The Prototype Pattern requires the interface to be implemented, and making the Dictionary class not be ICloneable will make things much more complicated for users down the line.
    – Lockethot
    Nov 8 at 15:04










  • Note that ICloneable is a horrible interface and should not be used. Almost every time someone uses this interface they expect it to behave different than what it does because peoples expectations to cloning things do not align. For instance, do you expect it to just clone the dictionary, or should the cloned dictionary also contain cloned keys and cloned values? What about objects referred to from these cloned values, should they be cloned as well? You're almost always better off writing your own clone method exactly like you expect it to be.
    – Lasse Vågsæther Karlsen
    Nov 8 at 15:04










  • I posted the above comment as a comment because this is my opinion, and should be seen in a different light compared to my answer which is more listing why you cannot do it and existing efforts in this kind of thing.
    – Lasse Vågsæther Karlsen
    Nov 8 at 15:06










  • I think I may do the ICloneable dictionary suggestion you just added. Seems to be the best solution to this problem.
    – Lockethot
    Nov 8 at 15:07


















  • I appreciate the answer, though it is upsetting that I cannot achieve the desired result. The example you show with code is exactly the problem I'm worried about. The Prototype Pattern requires the interface to be implemented, and making the Dictionary class not be ICloneable will make things much more complicated for users down the line.
    – Lockethot
    Nov 8 at 15:04










  • Note that ICloneable is a horrible interface and should not be used. Almost every time someone uses this interface they expect it to behave different than what it does because peoples expectations to cloning things do not align. For instance, do you expect it to just clone the dictionary, or should the cloned dictionary also contain cloned keys and cloned values? What about objects referred to from these cloned values, should they be cloned as well? You're almost always better off writing your own clone method exactly like you expect it to be.
    – Lasse Vågsæther Karlsen
    Nov 8 at 15:04










  • I posted the above comment as a comment because this is my opinion, and should be seen in a different light compared to my answer which is more listing why you cannot do it and existing efforts in this kind of thing.
    – Lasse Vågsæther Karlsen
    Nov 8 at 15:06










  • I think I may do the ICloneable dictionary suggestion you just added. Seems to be the best solution to this problem.
    – Lockethot
    Nov 8 at 15:07
















I appreciate the answer, though it is upsetting that I cannot achieve the desired result. The example you show with code is exactly the problem I'm worried about. The Prototype Pattern requires the interface to be implemented, and making the Dictionary class not be ICloneable will make things much more complicated for users down the line.
– Lockethot
Nov 8 at 15:04




I appreciate the answer, though it is upsetting that I cannot achieve the desired result. The example you show with code is exactly the problem I'm worried about. The Prototype Pattern requires the interface to be implemented, and making the Dictionary class not be ICloneable will make things much more complicated for users down the line.
– Lockethot
Nov 8 at 15:04












Note that ICloneable is a horrible interface and should not be used. Almost every time someone uses this interface they expect it to behave different than what it does because peoples expectations to cloning things do not align. For instance, do you expect it to just clone the dictionary, or should the cloned dictionary also contain cloned keys and cloned values? What about objects referred to from these cloned values, should they be cloned as well? You're almost always better off writing your own clone method exactly like you expect it to be.
– Lasse Vågsæther Karlsen
Nov 8 at 15:04




Note that ICloneable is a horrible interface and should not be used. Almost every time someone uses this interface they expect it to behave different than what it does because peoples expectations to cloning things do not align. For instance, do you expect it to just clone the dictionary, or should the cloned dictionary also contain cloned keys and cloned values? What about objects referred to from these cloned values, should they be cloned as well? You're almost always better off writing your own clone method exactly like you expect it to be.
– Lasse Vågsæther Karlsen
Nov 8 at 15:04












I posted the above comment as a comment because this is my opinion, and should be seen in a different light compared to my answer which is more listing why you cannot do it and existing efforts in this kind of thing.
– Lasse Vågsæther Karlsen
Nov 8 at 15:06




I posted the above comment as a comment because this is my opinion, and should be seen in a different light compared to my answer which is more listing why you cannot do it and existing efforts in this kind of thing.
– Lasse Vågsæther Karlsen
Nov 8 at 15:06












I think I may do the ICloneable dictionary suggestion you just added. Seems to be the best solution to this problem.
– Lockethot
Nov 8 at 15:07




I think I may do the ICloneable dictionary suggestion you just added. Seems to be the best solution to this problem.
– Lockethot
Nov 8 at 15:07


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53209390%2fhow-do-you-extend-classes-and-structs-with-interfaces-via-extension-in-c%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







這個網誌中的熱門文章

Xamarin.form Move up view when keyboard appear

Post-Redirect-Get with Spring WebFlux and Thymeleaf

Anylogic : not able to use stopDelay()