C# Force subclasses to implement a static method The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experienceWhat is the difference between String and string in C#?Cast int to enum in C#How do I enumerate an enum in C#?What are the correct version numbers for C#?Why is it important to override GetHashCode when Equals method is overridden?Why can't I define a static method in a Java interface?Understanding Python super() with __init__() methodsStatic methods in Python?Why doesn't Java allow overriding of static methods?Java: when to use static methods

Semisimplicity of the category of coherent sheaves?

What's the point in a preamp?

Didn't get enough time to take a Coding Test - what to do now?

Does the AirPods case need to be around while listening via an iOS Device?

Can withdrawing asylum be illegal?

How can I protect witches in combat who wear limited clothing?

How to copy the contents of all files with a certain name into a new file?

Typeface like Times New Roman but with "tied" percent sign

Did the new image of black hole confirm the general theory of relativity?

How do I add random spotting to the same face in cycles?

Is a pteranodon too powerful as a beast companion for a beast master?

Do working physicists consider Newtonian mechanics to be "falsified"?

Scientific Reports - Significant Figures

Is this wall load bearing? Blueprints and photos attached

How do you keep chess fun when your opponent constantly beats you?

Was credit for the black hole image misattributed?

Empty set is subset of every set? If yes, why that...

How to pronounce 1ターン?

Grover's algorithm - DES circuit as oracle?

Python - Fishing Simulator

How to politely respond to generic emails requesting a PhD/job in my lab? Without wasting too much time

Match Roman Numerals

What aspect of planet Earth must be changed to prevent the industrial revolution?

Did the UK government pay "millions and millions of dollars" to try to snag Julian Assange?



C# Force subclasses to implement a static method



The 2019 Stack Overflow Developer Survey Results Are In
Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
The Ask Question Wizard is Live!
Data science time! April 2019 and salary with experienceWhat is the difference between String and string in C#?Cast int to enum in C#How do I enumerate an enum in C#?What are the correct version numbers for C#?Why is it important to override GetHashCode when Equals method is overridden?Why can't I define a static method in a Java interface?Understanding Python super() with __init__() methodsStatic methods in Python?Why doesn't Java allow overriding of static methods?Java: when to use static methods



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I am currently building a class library to handle unit measurements and I wanted to use the factory pattern with static methods to create lengths or areas and so on.



To keep the methods consistent I wanted to create an interface or a superclass. Is there a possible way to enforce subclasses to implement a static method?



(Offtopic: Is it also possible to enforce subclasses to overload operators?)



For example:



public class Length
...


public static Length Create(double value, string unitCode)

var length = new Length();

switch (unitCode)

case "Mm":
length.Megameters = value;
break;
case "Km":
case "km":
length.Kilometers = value;
break;
case "hm":
length.Hectometers = value;
break;
case "dam":
length.Decameters = value;
break;
case "m":
length.Meters = value;
break;
case "dm":
length.Decimeters = value;
break;
case "cm":
length.Centimeters = value;
break;
case "mm":
length.Millimeters = value;
break;
case "µm":
length.Micrometers = value;
break;
case "pm":
length.Picometers = value;
break;
case "in":
length.Inches = value;
break;
case "ft":
length.Feet = value;
break;
case "yd":
length.Yards = value;
break;
case "mi":
length.Miles = value;
break;
case "smi":
length.ScandinavianMiles = value;
break;
case "ly":
length.LightYears = value;
break;
case "NM":
length.NauticalMiles = value;
break;
case "ftm":
length.Fathoms = value;
break;
case "fur":
length.Furlongs = value;
break;
case "ua":
length.AstronomicalUnits = value;
break;
case "pc":
length.Parsecs = value;
break;
default:
throw new ArgumentException("Not a valid unit given.", nameof(unitCode));

return length;

...









share|improve this question






















  • It's impossible to do that. The nearest thing you can do is an Extension Method or enforce it through Reflection.

    – Luke Vo
    Mar 8 at 13:22











  • Interfaces can only force instance members, but since static members can't be overriden anyway, if you have a single base class for all your subclasses they will all share whatever static members the base class have.

    – Zohar Peled
    Mar 8 at 13:24











  • Why would subclass at all needs to implement that since that method is anyways available to subclass

    – Rahul
    Mar 8 at 13:26











  • BTW, why don't you keep a single property for length and a single property for units? That would make your code much simpler. I would also implement a length converter that would take the length and the source unit and translate it to the target unit - if that's something you do in your application.

    – Zohar Peled
    Mar 8 at 13:27












  • @Luke, I think extension methods wouldn't help in this case. I just want keep the code constistent for all classes which have sth. to do with unit of measurement. These properties are pointing to the same private attribute, they just use different coefficients to write or read the attribute.

    – Ayoko
    Mar 8 at 14:03


















0















I am currently building a class library to handle unit measurements and I wanted to use the factory pattern with static methods to create lengths or areas and so on.



To keep the methods consistent I wanted to create an interface or a superclass. Is there a possible way to enforce subclasses to implement a static method?



(Offtopic: Is it also possible to enforce subclasses to overload operators?)



For example:



public class Length
...


public static Length Create(double value, string unitCode)

var length = new Length();

switch (unitCode)

case "Mm":
length.Megameters = value;
break;
case "Km":
case "km":
length.Kilometers = value;
break;
case "hm":
length.Hectometers = value;
break;
case "dam":
length.Decameters = value;
break;
case "m":
length.Meters = value;
break;
case "dm":
length.Decimeters = value;
break;
case "cm":
length.Centimeters = value;
break;
case "mm":
length.Millimeters = value;
break;
case "µm":
length.Micrometers = value;
break;
case "pm":
length.Picometers = value;
break;
case "in":
length.Inches = value;
break;
case "ft":
length.Feet = value;
break;
case "yd":
length.Yards = value;
break;
case "mi":
length.Miles = value;
break;
case "smi":
length.ScandinavianMiles = value;
break;
case "ly":
length.LightYears = value;
break;
case "NM":
length.NauticalMiles = value;
break;
case "ftm":
length.Fathoms = value;
break;
case "fur":
length.Furlongs = value;
break;
case "ua":
length.AstronomicalUnits = value;
break;
case "pc":
length.Parsecs = value;
break;
default:
throw new ArgumentException("Not a valid unit given.", nameof(unitCode));

return length;

...









share|improve this question






















  • It's impossible to do that. The nearest thing you can do is an Extension Method or enforce it through Reflection.

    – Luke Vo
    Mar 8 at 13:22











  • Interfaces can only force instance members, but since static members can't be overriden anyway, if you have a single base class for all your subclasses they will all share whatever static members the base class have.

    – Zohar Peled
    Mar 8 at 13:24











  • Why would subclass at all needs to implement that since that method is anyways available to subclass

    – Rahul
    Mar 8 at 13:26











  • BTW, why don't you keep a single property for length and a single property for units? That would make your code much simpler. I would also implement a length converter that would take the length and the source unit and translate it to the target unit - if that's something you do in your application.

    – Zohar Peled
    Mar 8 at 13:27












  • @Luke, I think extension methods wouldn't help in this case. I just want keep the code constistent for all classes which have sth. to do with unit of measurement. These properties are pointing to the same private attribute, they just use different coefficients to write or read the attribute.

    – Ayoko
    Mar 8 at 14:03














0












0








0








I am currently building a class library to handle unit measurements and I wanted to use the factory pattern with static methods to create lengths or areas and so on.



To keep the methods consistent I wanted to create an interface or a superclass. Is there a possible way to enforce subclasses to implement a static method?



(Offtopic: Is it also possible to enforce subclasses to overload operators?)



For example:



public class Length
...


public static Length Create(double value, string unitCode)

var length = new Length();

switch (unitCode)

case "Mm":
length.Megameters = value;
break;
case "Km":
case "km":
length.Kilometers = value;
break;
case "hm":
length.Hectometers = value;
break;
case "dam":
length.Decameters = value;
break;
case "m":
length.Meters = value;
break;
case "dm":
length.Decimeters = value;
break;
case "cm":
length.Centimeters = value;
break;
case "mm":
length.Millimeters = value;
break;
case "µm":
length.Micrometers = value;
break;
case "pm":
length.Picometers = value;
break;
case "in":
length.Inches = value;
break;
case "ft":
length.Feet = value;
break;
case "yd":
length.Yards = value;
break;
case "mi":
length.Miles = value;
break;
case "smi":
length.ScandinavianMiles = value;
break;
case "ly":
length.LightYears = value;
break;
case "NM":
length.NauticalMiles = value;
break;
case "ftm":
length.Fathoms = value;
break;
case "fur":
length.Furlongs = value;
break;
case "ua":
length.AstronomicalUnits = value;
break;
case "pc":
length.Parsecs = value;
break;
default:
throw new ArgumentException("Not a valid unit given.", nameof(unitCode));

return length;

...









share|improve this question














I am currently building a class library to handle unit measurements and I wanted to use the factory pattern with static methods to create lengths or areas and so on.



To keep the methods consistent I wanted to create an interface or a superclass. Is there a possible way to enforce subclasses to implement a static method?



(Offtopic: Is it also possible to enforce subclasses to overload operators?)



For example:



public class Length
...


public static Length Create(double value, string unitCode)

var length = new Length();

switch (unitCode)

case "Mm":
length.Megameters = value;
break;
case "Km":
case "km":
length.Kilometers = value;
break;
case "hm":
length.Hectometers = value;
break;
case "dam":
length.Decameters = value;
break;
case "m":
length.Meters = value;
break;
case "dm":
length.Decimeters = value;
break;
case "cm":
length.Centimeters = value;
break;
case "mm":
length.Millimeters = value;
break;
case "µm":
length.Micrometers = value;
break;
case "pm":
length.Picometers = value;
break;
case "in":
length.Inches = value;
break;
case "ft":
length.Feet = value;
break;
case "yd":
length.Yards = value;
break;
case "mi":
length.Miles = value;
break;
case "smi":
length.ScandinavianMiles = value;
break;
case "ly":
length.LightYears = value;
break;
case "NM":
length.NauticalMiles = value;
break;
case "ftm":
length.Fathoms = value;
break;
case "fur":
length.Furlongs = value;
break;
case "ua":
length.AstronomicalUnits = value;
break;
case "pc":
length.Parsecs = value;
break;
default:
throw new ArgumentException("Not a valid unit given.", nameof(unitCode));

return length;

...






c# inheritance override static-methods






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 8 at 13:21









AyokoAyoko

42




42












  • It's impossible to do that. The nearest thing you can do is an Extension Method or enforce it through Reflection.

    – Luke Vo
    Mar 8 at 13:22











  • Interfaces can only force instance members, but since static members can't be overriden anyway, if you have a single base class for all your subclasses they will all share whatever static members the base class have.

    – Zohar Peled
    Mar 8 at 13:24











  • Why would subclass at all needs to implement that since that method is anyways available to subclass

    – Rahul
    Mar 8 at 13:26











  • BTW, why don't you keep a single property for length and a single property for units? That would make your code much simpler. I would also implement a length converter that would take the length and the source unit and translate it to the target unit - if that's something you do in your application.

    – Zohar Peled
    Mar 8 at 13:27












  • @Luke, I think extension methods wouldn't help in this case. I just want keep the code constistent for all classes which have sth. to do with unit of measurement. These properties are pointing to the same private attribute, they just use different coefficients to write or read the attribute.

    – Ayoko
    Mar 8 at 14:03


















  • It's impossible to do that. The nearest thing you can do is an Extension Method or enforce it through Reflection.

    – Luke Vo
    Mar 8 at 13:22











  • Interfaces can only force instance members, but since static members can't be overriden anyway, if you have a single base class for all your subclasses they will all share whatever static members the base class have.

    – Zohar Peled
    Mar 8 at 13:24











  • Why would subclass at all needs to implement that since that method is anyways available to subclass

    – Rahul
    Mar 8 at 13:26











  • BTW, why don't you keep a single property for length and a single property for units? That would make your code much simpler. I would also implement a length converter that would take the length and the source unit and translate it to the target unit - if that's something you do in your application.

    – Zohar Peled
    Mar 8 at 13:27












  • @Luke, I think extension methods wouldn't help in this case. I just want keep the code constistent for all classes which have sth. to do with unit of measurement. These properties are pointing to the same private attribute, they just use different coefficients to write or read the attribute.

    – Ayoko
    Mar 8 at 14:03

















It's impossible to do that. The nearest thing you can do is an Extension Method or enforce it through Reflection.

– Luke Vo
Mar 8 at 13:22





It's impossible to do that. The nearest thing you can do is an Extension Method or enforce it through Reflection.

– Luke Vo
Mar 8 at 13:22













Interfaces can only force instance members, but since static members can't be overriden anyway, if you have a single base class for all your subclasses they will all share whatever static members the base class have.

– Zohar Peled
Mar 8 at 13:24





Interfaces can only force instance members, but since static members can't be overriden anyway, if you have a single base class for all your subclasses they will all share whatever static members the base class have.

– Zohar Peled
Mar 8 at 13:24













Why would subclass at all needs to implement that since that method is anyways available to subclass

– Rahul
Mar 8 at 13:26





Why would subclass at all needs to implement that since that method is anyways available to subclass

– Rahul
Mar 8 at 13:26













BTW, why don't you keep a single property for length and a single property for units? That would make your code much simpler. I would also implement a length converter that would take the length and the source unit and translate it to the target unit - if that's something you do in your application.

– Zohar Peled
Mar 8 at 13:27






BTW, why don't you keep a single property for length and a single property for units? That would make your code much simpler. I would also implement a length converter that would take the length and the source unit and translate it to the target unit - if that's something you do in your application.

– Zohar Peled
Mar 8 at 13:27














@Luke, I think extension methods wouldn't help in this case. I just want keep the code constistent for all classes which have sth. to do with unit of measurement. These properties are pointing to the same private attribute, they just use different coefficients to write or read the attribute.

– Ayoko
Mar 8 at 14:03






@Luke, I think extension methods wouldn't help in this case. I just want keep the code constistent for all classes which have sth. to do with unit of measurement. These properties are pointing to the same private attribute, they just use different coefficients to write or read the attribute.

– Ayoko
Mar 8 at 14:03













0






active

oldest

votes












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',
autoActivateHeartbeat: false,
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%2f55064104%2fc-sharp-force-subclasses-to-implement-a-static-method%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes















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.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55064104%2fc-sharp-force-subclasses-to-implement-a-static-method%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







Popular posts from this blog

AWS Lex not identifying response if by a variable The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experienceEnforcing custom enumeration in AWS LEX for slot valuesHow to give response based on user response in Amazon Lex?Intercepting AWS Lambda Response to a AWS Lex QueryLex chat bot error: Reached second execution of fulfillment lambda on the same utteranceamazon lex showing invalid responseLambda response send back to Lex slot?Response card in Amazon lexAmazon Lex - Lambda response return HTML to botHow can I solve 424 (Failed Dependency) (python) obtained from Amazon lex?

Алба-Юлія

Захаров Федір Захарович