Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
How C#6 using static feature should be used in right way? It really looks nice for cases like shortening string.Format (CultureInfo.InvariantCulture, "Some format"); to Format (InvariantCulture, "Some format");, but is it always the case?
Take this for example. You have enum like this:
enum Enum { Value1, Value2 }
And you decide to to use it in code like this:
using static {Namespace}.Enum;
// ...
var value = Value1;
Latter on you decide to create a class named Value1. Then your code var value = Value1 will generate compile error:
'Value1' is a type, which is not valid in the given context
Or other case. You have two classes with different static methods:
class Foo {
public static void Method1() { }
}
class Foo2 {
public static void Method2() { }
}
And you use it in 3rd class like
using static {Namespace}.Foo;
using static {Namespace}.Foo2;
// ...
class Bar {
void Method() {
Method1();
Method2();
}
}
Which works fine. But if you decide to introduce Method2 in Foo class this code will generate compile error:
The call is ambiguous between the following methods or properties: 'Foo.Method2()' and 'Foo2.Method2()'
So my question is what is the right way of using using static feature?
The "problems" being stated were already present in previous versions of the language regarding type name resolution.
This feature just brings those "problems" down to type members.
I've not read any recommendations on the topic. But my opinion is that you can use using static for stuff that gives you names that makes sense on their own.
using static Math;
var max = Max(value1, value2);
In the case of string.Format I think it becomes unclear what Format means (all kinds of stuff can be formatted into anything that has a kind of format).
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I was looking for approaches that could be used to access a static class which contains private static methods to unit test.
I came across PrivateObject and PrivateType, I do not understand what the difference between them is, and how you would decided to use either one.
BusinessLogic
public static Class BarLogic(){
private static void FooBar(){
//do something here
}
}
API
public class FooService(){
BarLogic.FooBar();
}
The difference is whether you're accessing otherwise inaccessible instance members or static members.
In the example below, you would use PrivateObject to access _someInstanceField, and PrivateType to access _someStaticField.
public class SomeObjectWithInAccessibleMembers
{
private int _someInstanceField;
private static int _someStaticField;
}
Given that your test was in a separate assembly from this class (and therefore unable to to see its internal members) you could do this:
var privateObject = new PrivateObject(new SomeObjectWithInAccessibleMembers());
privateObject.SetField("_someInstanceField", 1);
Assert.AreEqual(1, privateObject.GetField("_someInstanceField"));
var privateType = new PrivateType(typeof(SomeObjectWithInAccessibleMembers));
privateType.SetStaticField("_someStaticField", 1);
Assert.AreEqual(1, privateType.GetStaticField("_someStaticField"));
I've never used this. I didn't even know about it. My first reaction is that it couples the test to the inner implementation of the class instead of testing its public methods. Then it couples it some more by using strings for member names, so the tests could break just by changing a member name.
On the other hand, I've worked in projects where a) I want to add unit tests, but b) I can't refactor to make it more testable. It's not my first choice but I might have a use for this. Thanks!
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I want to dynamically access classes in c# in the way like Java class.forName(). I have only found things like Class.forName() equivalent in .NET? but I don't want to create instances.
In detail: I have got a simple text file containing a list of classes. I read them using file.ReadLine() (so I have got all class names as strings) and then I want to execute the same static method on each class: class1.method(); class2.method; and so on. The classes all exist and I need to access them. How can I do that?
C# doesn't support static interfaces (or static members in interfaces), so unless you want to use factory classes (the usual approach), you'll need to use reflection to invoke the static method directly.
void Main()
{
Console.WriteLine(Type.GetType("A").GetMethod("Hi").Invoke(null, new object[] {}));
}
class A
{
public static string Hi() { return "Hi!"; }
}
You might want to use a fully-qualified name for the type to make this work really well. Using just the name of the type is tricky, especially when you're trying to invoke types from other assemblies (which you probably are, otherwise there'd be no reason to use reflection - just use a dictionary of delegates or whatever).
You can use System.Reflection to load the Assembly into memory and then drill down to the type followed by getting the required method and invoke.
Refer to the documentation
GetMethod
If you have names of your desired Type then you can use Type.GetType(string) method.
Example if you have a class like this :
namespace MeProgram.BusinessLogic
{
public class MeObject {}
}
Full class name of that object should be "MeProgram.BusinessLogic.MeObject".
Now you can use that name inside of Type.GetType(string) method like such :
string className = "MeProgram.BusinessLogic.MeObject";
Type classType = Type.GetType(className);
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I'm currently dealing with a long enum with roughly 100+ elements, where the first word in each element is used to categorize the entries:
public enum UserPermissions{
FilesRead,
FilesWrite,
FoldersRead,
FoldersWrite,
NotesCreate,
NotesDelete,
NotesModify,
...
...
}
I would like to categorize the permissions into a more organized structure using namespaces such as:
UserPermissions.Files.Read;
UserPermissions.Notes.Modify;
The main issue here is to maintain compatibility with existing code by avoiding or minimizing refactoring needed. What is the best solution?
My current idea is to convert the enum to a class:
public class UserPermissions
{
public enum Files{
Read = 1,
Write = 2,
}
public enum Folders
{
Read = 3,
Write = 4,
}
...
...
}
But this will require refactoring old code such as UserPermissions.FilesRead to UserPermissions.Files.Read.
If you realy do not want to refactor, you can provide both temporarly:
public enum UserPermissions{
FilesRead,
FilesWrite,
FoldersRead,
FoldersWrite,
NotesCreate,
NotesDelete,
NotesModify,
}
public class UserPermission //Other name then enum, or the class must be under a different namespace
{
public enum Files
{
Read = UserPermissions.FilesRead,
Write = UserPermissions.FilesWrite,
}
public enum Folders
{
Read = UserPermissions.FoldersRead,
Write = UserPermissions.FoldersWrite,
}
}
If you now have a method, you could simple cast (Folders)userPermission.
But you shouldn't do this. It's error prone (casting) and not according to DRY (Don't repeat your self). You should start refactoring instead.
Simple write your new enums, compile, fix, compile, fix, compile [...] -> success.
if you use one of them to save it to a database you should maintain the same number you had on your legacy code, otherwise you will run in trouble, changing the structure should not affect the behavior of your code, but you will need to refactor everything, so far that is the cost I am seeing here
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I have the common scenario of needing to write a pair of methods:
One that gets a result and throws an exception if it fails, and
a Try-variant of the same method that attempts to get the result as an out param, and returns a bool that indicates success status.
Here are two examples that illustrate the two approaches that I am considering. Which of these approaches provides the best performance? Also, is one approach likely to be easier to maintain than the other? I am also open to suggestions for other ways to implement this pair of methods.
Method 1: Foo() as master
public string GetAnswer(string question) {
string answer = null;
if(!this.TryGetAnswer(question, out answer)) {
throw new AnswerNotFoundException();
}
return answer;
}
public bool TryGetAnswer(string question, out string answer) {
answer = null;
//business logic
return answer != null;
}
Method 2: TryFoo() as master
public string GetAnswer(string question) {
//business logic
if(!answerFound) {
throw new AnswerNotFoundException();
}
return answer;
}
public bool TryGetAnswer(string question, out string answer) {
try {
answer = this.GetAnswer(question);
return true;
} catch (AnswerNotFoundException e) {
answer = null;
return false;
}
}
The point of the TryFoo() API pattern is to avoid the overhead of (potentially) throwing an exception that the companion Foo function does.
Your first example accomplishes this. Also note that the pattern in your first example is supported by Microsoft itself in its reference source for Boolean.TryParse and Boolean.Parse.†
Finally, note that Code Analysis will raise CA1021: Avoid out parameters if you include an out parameter in a public method. The question Code analysis comes back with suggestion about not using “out” parameters discusses this warning. The top-voted answer indicates that the TryParse idiom is well-established. Therefore, making use of the TryParse approach in a public API has a good chance of being well-received. So, a reasonable (though subjective) argument can made in this case to suppress warning CA1021.
† Links suggested by Damien_The_Unbeliever
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am working with C#.NET and basically have a page containing many areas.
In my code-behind, I basically want to be able to do something like:
bool result1 = MyClass.Section["area1"].Process();
bool result4 = MyClass.Section["area4"].Process();
I need to write a class that would call some kind of "Process" method and be able to have it accept a parameter like "area1" inside that method.
Any help on getting me started with this would be greatly appreciated, thank you!
Following the normal .NET naming conventions I'll assume you mean, by your example, that MyClass is being referenced statically rather than by instance (which may not be a big change). Given that assumption, it appears you have a class like:
static class MyClass
{
public static IIndexer Section { get; }
}
IIndexer in this case could be any type that implements an indexer property that takes a string and returns a type that has a method named Process which in turn returns a bool. IIndexer could theoretically look like:
interface IIndexer
{
ISomething this[string] { get; }
}
Next we'll fill in the ISomething blank above with a simple IProcess interface so we don't have to know anything about your specific implementation:
interface IProcess
{
bool Process();
}
So now the indexer above can be changed to:
IProcess this[string] { get; }
Of course, none of the above has any real executable code, but outlines the objects necessary to do what you're after. Now when you go to run your code using your fulfilled contracts the call chain is pretty simple:
bool result1 = MyClass.Section["area1"].Process();
// MyClass.Section > IIndexer.this[string] > IProcess.Process
To POC the idea, a good way to mock the IIndexer implementation might be to use Dictionary<string, IProcess> as it'll give you a usable indexer for your purposes.