In Objective-C (probably in C too) I can have a header file which can contain just anything from macros to constants. And any class (actually the file it resides) that imports that header file can see and use whatever there is declared. Isn't there a similar way to do this in C#? I have not found anything helpful so far. What I can do in C# is have a collection of static classes each having constant fields in them. But when I want to access those constants I have no other way but say Classname.ConstantName. That Classname part is really inconvenient.
You can make your life a little easier by specifying an alias for your class name:
using G = MyNamespace.MyClassContainingGlobalConstants;
...
var x = G.MyConstant;
Apart from that, I'm not aware of any C# feature that would allow you to access static class members without some kind of class name. (BTW, VB.NET has Modules for this purpose.)
Related
For localization I have one resx file per XAML file. They lie in the same directory and namespace. The resx name corresponds to the XAML name with the word Resources appended.
I access the resources like this:
<TextBlock Text="{x:Static r:MainWindowResources.SomeText}"/>
Since I find this quite lengthy (and there are even longer class names) I was wondering if there was some way I could define an alias to MainWindowResources. In C# I can do this with a using directive.
It would be a lot easier if the generated resource file wrapper wouldn't be a class with static properties. A possible solution would be to use a wrapper instance which inherits from DynamicObject. You could pass it a type and access the type's static members through it. Then you'd add an instance of this wrapper as a resource in XAML.
But I'd lose IntelliSense support and it probably wouldn't be great performance-wise either.
Another solution would be to use the WPF Localization Extension but I'd also lose IntelliSense support. Plus I'm curios whether there is any other way to create an alias to a static class. :)
No, there is no way to simply alias the class name in Xaml like you would in C# with using.
A custom markup extension with a short name is probably the best you could do, but as you say, you would lose editor completion support. If you're really desperate, you could write a T4 template that would generate an enum with one value for each string in your resource file, and then you could use an enum value as your markup extension parameter with completion support (e.g., {l:MainWindowString SomeText}), but that seems like a lot of work just to shorten some Xaml attributes, and they wouldn't be that much shorter.
I would just stick with what you have.
I have a VSTO (Excel) project written in C#. Three questions:
I have a lot of variables that are populated once and then referenced extensively throughout the project. So I created a public static class which I called "Omni" - since that is both descriptive and short. Is something like this the recommended approach?
I put common functions in a public static class that I named "Utilities". I then used the "this" keyword as the first parameter, making them extension methods. They can then be accessed from anywhere - without using a "Utilities." prefix (although I'm not exactly sure why). Same question: is this the preferred way of doing this?
Finally, I have some common 'subroutines', i.e., public void methods. So parameters are passed in and processed, but nothing is returned. Should such common code just go in its own appropriately named public static class and then get called with the class name as a prefix? If so, is there any convention as to what the name of the class would be?
I realize these are newbie type questions (and I have been searching for a while!). Thanks.
Regarding your points
I have a lot of variables that are populated once and then referenced
extensively throughout the project. So I created a public static class
which I called "Omni" - since that is both descriptive and short. Is
something like this the recommended approach?
Yes, it is common practise to centralize for example string constants that
are often used.
If you have more of those, I would start to structure those to different
classes.
If you want that to be flexible and e.g. have cases where there are
mappings between constants, like Green = 1, I would move to some
enumeration value technology.
More on that idea can be found in this article
If the value does not change between different starts of your application,
check if you can use resources for that, which is often a good choice
for string constants to.
I put common functions in a public static class that I named
"Utilities". I then used the "this" keyword as the first parameter,
making them extension methods. They can then be accessed from
anywhere - without using a "Utilities." prefix (although I'm not
exactly sure why). Same question: is this the preferred way of doing
this?
Extension methods are a handy way of getting things like conversions done.
Just do not everything as an extension, just conversions as a rule of thumb.
Finally, I have some common 'subroutines', i.e., public void methods.
So parameters are passed in and processed, but nothing is returned.
Should such common code just go in its own appropriately named public
static class and then get called with the class name as a prefix? If
so, is there any convention as to what the name of the class would be?
This, in opposite of the others, looks like a design flaw.
Perhaps you can provide more information on what those subroutines do.
In object oriented code, code is distributed near the objects it is working
with. If you depend heavily on code that is in static classes, probably there
is something wrong. Do your static classes have members? Do they share some
knowledge between different calls to your static classes?
I'm working on a C# library (let's just call it "Foo" for the sake of this question). It has some needs very similar to standard .NET needs: for example, it provides some drawing services, and some conversion services.
For the sake of familiarity and users of the library being able to guess what things are called, I'd like to follow the .NET standard, and name these parts of the library Foo.Drawing and Foo.Convert (and so on). But I'm finding that in actual use, this causes pain. People almost always have "using System;" at the top of each file, and when using this library, they want to have "using Foo;" as well. But now they have two Drawing and two Convert modules, and hilarity ensues.
For example, now instead of just using Drawing.Color for a parameter or variable type, you have to explicitly spell out System.Drawing.Color, or the compiler complains that Foo.Drawing doesn't have a Color type. Similarly, you want to use a standard Convert.ToInt32, you have to say System.Convert.ToInt32, even though you're already using System, because otherwise it finds Foo.Convert and fails to find ToInt32.
I understand why all this is as it is, but I'm still new to the C# community, so I don't know which is the most standard solution:
Leave it this way, and expect users to use fully-qualified names where necessary?
Rename the conflicting modules to something else (maybe Foo.Graphics instead of Foo.Drawing, and Foo.Conversion instead of Foo.Convert)?
Use some prefix on the standard names (Foo.FDrawing and Foo.FConvert)?
Something else?
Any advice from you more experienced C# gurus will be appreciated!
You can use namespace aliasing :
using System;
using FConvert = Foo.Convert;
public class Bar
{
public void Test()
{
var a = Convert.ToInt32("1");
var b = FConvert.ToInt32("1");
}
}
One of the main usage of namespaces is to avoid name clashing.
It means that namespaces allow developers to create types with identical names, as long as the belong to different namespaces.
A library usually have at least a root namespace, and possibly nested namespaces that logically groups the related types.
Name your types as you wish, as long as the names are meaningful and represent what the type really are. A client of your library expects a type named Animal to represent an Animal, not something else. The same applies for naming namespaces.
However, avoid at all cost the names from System, since it will be really annoying for your library clients (as you described) to deal with conflicting names all over the place.
A common way to deal with conflicting namesapces inside a class is to use namespace aliasing:
using FooConvert = Foo.Convert;
using BarConvert = Bar.Convert;
Its said that most high-level dynamically types languages are reflexive. Reflection (computer programming) on Wikipedia explains but it doesn't really give a very clear picture of what it means. Can anyone explain it in a simpler way by a relevant example?
To give you a example how to use Reflection in a practical way:
Let's assume you are developing an Application which you'd like to extend using plugins. These plugins are simple Assemblies containing just a class named Person:
namespace MyObjects
{
public class Person
{
public Person() { ... Logic setting pre and postname ... }
private string _prename;
private string _postname;
public string GetName() { ... concat variabes and return ... }
}
}
Well, plugins should extend your application at runtime. That means, that the content and logic should be loaded from another assembly when your application already runs. This means that these resources are not compiled into your Assembly, i.e. MyApplication.exe. Lets assume they are located in a library: MyObjects.Person.dll.
You are now faced with the fact that you'll need to extract this Information and for example access the GetName() function from MyObjects.Person.
// Create an assembly object to load our classes
Assembly testAssembly = Assembly.LoadFile(Application.StartUpPath + #"MyObjects.Person.dll");
Type objType = testAssembly.GetType("MyObjects.Person");
// Create an instace of MyObjects.Person
var instance = Activator.CreateInstance(objType);
// Call the method
string fullname = (string)calcType.InvokeMember("GetName",
BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public,
null, instance, null);
As you can see, you could use System.Reflection for dynamic load of Resources on Runtime. This might be a help understanding the ways you can use it.
Have a look on this page to see examples how to access assemblys in more detail. It's basically the same content i wrote.
To better understand reflection, think of an interpreter that evaluates a program. The interpreter is a program that evaluates other programs.
The program can (1) inspect and (2) modify its (a) own state/behavior, or the state/behavior of the interperter running it (b).
There are then four combinations. Here is an example of each kind of action:
1a -- Read the list of fields an object has
2a -- Modification of the value of one field based on the name of the field; reflective invocation of methods.
1b -- Inspect the current stack to know what is the current method that is executed
2b -- Modify the stack or how certain operations in the language are executed (e.g. message send).
Type a is called structural reflection. Type b is called behavioral reflection. Reflection of type a is fairly easy to achieve in a language. Reflection of type b is way more complicated, especially 2b--this is an open research topic. What most people understand by reflection is 1a and 2a.
It is important to understand the concept of reification to understand reflection. When a statement in the program that is interpreted is evaluated, the interpreter needs to represent it. The intepreter has probably objects to model field, methods, etc. of the program to be interpreted. After all, the interpreter is a program as well. With reflection, the interpreted program can obtain references to objects in the interpreter that represent its own structure. This is reification. (The next step would be to understand causal connection)
There are various kinds of reflective features and it's sometimes confusing to understand what's reflective or not, and what it means. Thinking in term of program and interpreter. I hope it will help you understand the wikipedia page (which could be improved).
Reflection is the ability to query the metadata the program that you wrote in run-time, For example : What classes are found inside an assembly, What methods, fields and properties those classes contains, and more.
.net contains even 'attributes', those are classes that you can decorate with them classes, methods, fields and more, And all their purpose is to add customized metadata that you can query in run-time.
Many time details depend on metadata only. At the time of validation we don't care about string or int but we care that it should not be null. So, in that case you need a property or attribute to check without caring about specific class. There reflection comes in picture. And same way if you like to generate methods on a fly, (as available in dynamic object of C# 4.0), than also it is possible using reflection. Basically it help to do behavior driven or aspect oriented programming.
Another popular use is Testing framework. They use reflection to find methods to test and run it in proxy environment.
It is the ability of a programming langauge to adapt it's behaviour based upon runtime information.
In the .Net/C# world this is used frequently.
For example when serializing data to xml an attribute can be added to specify the name of the field in the resultant xml.
This is probably a better question for programmers.stackexchange.com.
But it basically just means that you can look at your code from within your code.
Back in my VB6 days there were some UI objects that had a Text property and others that had a Description (or something other than 'Text' anyway, I forget). It was a pain because I couldn't encapsulate code to deal with both kinds of objects the same way. With reflection I would have at least been able to look and see whether an object had a Text or a Description property.
Or sometimes objects might both have a Text property, but they derive from different base classes and don't have any interface applied to them. Again, it's hard to encapsulate code like this in a statically typed language without the help of reflection, but with reflection even a statically typed language can deal with it.
What is and how can it be used in C#.
Can you use the same concept in Python/Perl?
A partial type (it doesn't have to be a class; structs and interfaces can be partial too) is basically a single type which has its code spread across multiple files.
The main use for this is to allow a code generator (e.g. a Visual Studio designer) to "own" one file, while hand-written code is put in another.
I've no idea whether Python/Perl have the same capabilities, I'm afraid.
The c# partial class has been already explained here so I'll just cover the python part. You can use multiple inheritance to elegantly distribute the definition of a class.
class A_part1:
def m1(self):
print "m1"
class A_part2:
def m2(self):
print "m2"
class A(A_part1, A_part2):
pass
a = A()
a.m1()
a.m2()
A partial class is simply a class that's contained in more than one file. Sometimes it's so that one part can be machine-generated, and another part user-edited.
I use them in C# when I'm making a class that's getting a bit too large. I'll put the accessors and constructors in one file, and all of the interesting methods in a different file.
In Perl, you'd simply have two (or more) files that each declare themselves to be in a package:
(main program)
use MyClass;
(in MyClass.pm)
use MyClassOtherStuff;
package MyClass;
# [..class code here...]
(in MyClassOtherStuff.pm)
package MyClass;
# [...rest of code here...]
The concept of partial types have already been explained.
This can be done in python. As an example, do the following in a python shell.
class A(object):
pass
obj = A()
def _some_method(self):
print self.__class__
A.identify = _some_method
obj.identify()
Because python is a dynamic language you don't need a concept like partial class. In python is possible to extend object with functionality in runtime so it possible to break class declaration into different files
A Partial type is a type whose declaration is separated across multiple files. It makes sense to use them if you have a big class, which is hard to handle and read for a typical developer, to separate that class definition in separate files and to put in each file a logically separated section of code (for instance all public methods and proprieties in one file, private in other, db handling code in third and so on..)
No you don't have the same syntactical element in Python.
Python also has meta classes but that is more like a template class than a partial class. A good example of meta class usage is the Django ORM. All of your table models inherit from a base model class which also gets functionality included from a meta class. It is a pretty cool concept that enables an active record like pattern (is it full active record?).
Partial class comes handy when you have auto-generated code by some tool. Refer question Project structure for Schema First Service Development using WCF for an example.
You can put your logic in the partial class. Even if the auto-generated file is destroyed and recreated, your logic will persist in the partial class.