Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Require a class to be instanced in C#?

We need to "protect" a class from having static methods for security purposes. We don't want newbie devs following suggestions of coding tools to make a member static as we need to use a constructor with a password to control access to this class.

Is there any way to protect a .NET class in C# to prevent it from have any static members?

Would such a feature, if not available, be worthwhile for a future version of .NET?

Thank you.

like image 219
Neal Avatar asked Mar 27 '12 22:03

Neal


People also ask

Can a class be an instance?

Class Methods The first parameter of a class method is a reference to a class, i.e. a class object. They can be called via an instance or the class name.

How do I set an instance of a class?

Instantiating a Class When you create an object, you are creating an instance of a class, therefore "instantiating" a class. The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate.

Can we implement classes in C?

This document describes the simplest possible coding style for making classes in C. It will describe constructors, instance variables, instance methods, class variables, class methods, inheritance, polymorphism, namespaces with aliasing and put it all together in an example project.


2 Answers

we need to use a constructor with a password to control access to this class.

This sounds like a monumentally bad idea, but of course I know nothing about the security problem you're trying to solve. This is the far more interesting question than your question: What is the threat you are attempting to protect against? There is probably a better way to do it.

Is there any way to protect a .NET class in C# to prevent it from have any static members?

Have senior developers review the checkins of junior developers. Which you should be doing anyway, but particularly if the class has some kind of security semantics.

Would such a feature, if not available, be worthwhile for a future version of .NET?

That's unlikely in the extreme.

Thank you.

You're welcome!

like image 101
Eric Lippert Avatar answered Sep 29 '22 14:09

Eric Lippert


The easiest thing to do would be to set-up FxCop on your build server and write a custom FxCop rule to check for static members.

This question has details on how to write a custom FxCop rule.


Alternatively, as SimpleCoder pointed out, you can use StyleCop to enforce the rule on the source code.

This page describes how to set-up StyleCop with msbuild.

like image 26
Dan Rigby Avatar answered Sep 29 '22 15:09

Dan Rigby