C#: What's the purpose of Attributes/Reflection?

Started by
4 comments, last by Toolmaker 19 years, 11 months ago
I can''t seem to grasp the general ideas behind Attributes and reflection in C#? Can someone point me out what it is, what the use of it is and the finer details? I read "A Programmer''s Introduction to C#" but I can''t really grasp the concept from there. The same goes for interfaces and delegates. What''s the idea behind those? Toolmaker

Advertisement
Reflection allows you to determine information about types and objects inside an assembly at runtime. Attributes are the mechanism by which you attach additional information to these objects. Take a look through MSDN to see examples of reflection in action. One common usage is the creation of scripting engines. Since you only know the type at runtime (using script files), when the scripts are loaded and executed, reflection allows the scripts to create the types at runtime, since you can get the information about the types at runtime. Ever read about people you wanted to something like this - string myObject = "CMyClass"; - in C++ or the like? Reflection is what would be used to do this. Unfortunately raw C++ doesn't have a reflection library, but languages like Java and C# (and other .NET languages) do.

Interfaces - basically, you tell subclasses what they have to implement, and then clients can access the implementations through the interface, without worrying about how the actual interface is implemented. Let's say you have the interface IArray, which has some common array methods: addition, removal, and traditional index access via the [] operator. Now, let's say you have two classes CArray (actually implementations now) and CLinkedList which both implement IArray. The idea is that the client can use IArray without worrying how it's implemented. As you can see, one classes implements it uses arrays, however another implements it using linked lists. It doesn't matter how it's implemented though, as long as the interface works the way it's supposed to. Thus the linked list class has to implement the [] operator whether it likes it or not if it wants to implement the IArray interface.

From a more practical standpoint, interfaces allow you to write code that, well, actually interfaces with certain features in C# and other areas of the framework. For example, Array.Sort uses QuickSort to sort elements in an array. To make use of this functionality, the objects of the array have to implement IComparable, which has a CompareTo function. However, once it's implemented, you have access to this great utility function. It doesn't really care what the object is, as long as it has the CompareTo function to work with. IEnumberable means that your class can be enumerated, or iterated over. Implement this interface, and you can use the foreach mechanism in C#. Also cool. In closing, interfaces are just that - they allow you to interface "generically" with client code, regardless of implementation. As long as your implementation actually works, that is.

Delegates - Like function pointers, but with some additional usages and features. Commonly used as a callback mechanism. Someone else can elaborate on the intricacies.

The best way to learn about all these things is simply through experience. I can tell you about how all these things work but it's when you actually sit down and get things working together that you truly appreciate everything

[edited by - Zipster on May 11, 2004 6:05:13 AM]
quote:Original post by Toolmaker
I can''t seem to grasp the general ideas behind Attributes

Attributes are metadata about constructs in your program.

Some predefined attributes have magical special meanings to the compiler, such as Conditional. Some other attributes have special meanings to the linker, such as DllImport.

Attributes that you define yourself have no special meaning to the system. For example, there is currently no way to define an attribute that automatically causes a complex function to cache return values. Later versions of C# could allow attributes to be used in this way, but I would guess it''s unlikely to happen in the near future.

So what use are custom attributes? You can use reflection to extract custom attributes from constructs. The C# manual gives an example of a HelpAttribute attribute that specifies where to find help about a construct. If you were writing a C# IDE, you could use that attribute to show context sensitive help.

Another possible use would be a TransientAttribute class which you could attach to fields which should not be serialised (such as fields whose values can be determined from other fields, or fields that you don''t want to store on disk, such as passwords). This might be useful if you wanted to write the state of a game to disk, but didn''t want to have to write serialisation methods for each class.
quote:
and reflection

Reflection allows you to examine the structure of classes, fields, methods and other constructs of the C# program. Note that you can''t use reflection to examine the statements and expressions of method bodies -- that information is not available after compilation.
quote:
in C#?

Can someone point me out what it is, what the use of it is and the finer details? I read "A Programmer''s Introduction to C#" but I can''t really grasp the concept from there.

The same goes for interfaces

Loosely, an interface defines a kind of class. Whilst a class contains definitions of fields and methods, an interface contains only declarations of fields and methods.

When a class derives from an interface, it is essentially saying: I provide the methods and fields declared by this interface.

Deriving from a class is slightly different: The subclass might not provide the methods and fields defined in a superclass, because it may just use the superclass''s versions of those.

<Aside>
IMO, C# gets interfaces wrong. Interfaces should define a kind of class, but classes should automatically be considered implementations of the interface if they provide the fields and methods that the interface declares. However, this does mean that some classes could appear to implement an interface whilst they actually don''t, which could be bad.

A good middle ground which wouldn''t break existing code could be to allow ''retroactive abstraction'' -- allowing statements of the form class Foo: IBar; to indicate that the previously defined class Foo implements IBar.
</Aside>
quote:
and delegates.

Delegates are like function pointers, except that they are pointers to methods bound to a particular instance. Essentially, when a delegate for theInstance.theMethod is called, the method is called on that particular instance. It''s useful if you want a particular method to be called when something happens -- register the delegate with some source of notifications, and it''ll invoke the delegate when it happens.
quote:
What''s the idea behind those?

Toolmaker


CoV
That makes sense . I don''t think I am going to use reflection/attributes in the near future, but having some basic knowledge is usefull.

So, interfaces are more or less abstract classes(Or in C++ speak, pure virtual classes) which forces the implementing class to override them.

One thing I don''t get about it, why just don''t use abstract classes in this case? Or am I getting it wrong here? Or do you use interfaces as a generic interface? E.g, some functions wants a reference of ICustomArray for handling(For instance, foreach) data in it. Wether ICustomArray is hardcoded, linked listed, stored inside a database or uses the surface of the moon to get it''s data isn''t of importance. All have to do it implement the interface, create an instance of CMyClass and cast it back to ICustomArray and then pass this to the function? But doesn''t a base class work there too?

I am aware foreach uses IEnumberable, but it was as an example.

Toolmaker


My site
/* -Earth is 98% full. Please delete anybody you can.*/

quote:Original post by Toolmaker
So, interfaces are more or less abstract classes(Or in C++ speak, pure virtual classes) which forces the implementing class to override them.

More or less. Of course, as in C++, you don''t have to implement a particular method, but you end up with a class you can''t construct.
quote:
One thing I don''t get about it, why just don''t use abstract classes in this case? Or am I getting it wrong here? Or do you use interfaces as a generic interface? E.g, some functions wants a reference of ICustomArray for handling(For instance, foreach) data in it. Wether ICustomArray is hardcoded, linked listed, stored inside a database or uses the surface of the moon to get it''s data isn''t of importance. All have to do it implement the interface, create an instance of CMyClass and cast it back to ICustomArray and then pass this to the function? But doesn''t a base class work there too?

Yes. However, sometimes you need to have a class that supports more than one distinct set of features. For example, a database might have a RecordSet class that needs to support certain features common to all database classes (for example, an Owner property), but also needs to act as a Container, since it contains Records.

C# doesn''t allow you to subclass both Container and DatabaseObject -- you can only inherit from one class, even if the other classes are entirely abstract. Thus, interfaces are used as a replacement for abstract classes.

There is, in principle, no difference between interfaces and abstract classes. The difference is only there because you aren''t allowed to inherit from more than one class.
CoV
Slightly OT, but I've never had a major problem with multiple-inheritance(MI), and Borland's OWL (equiv. of MFC) worked brilliantly by making use of it, unlike MFC's Single Inheritance.

I know there are loads of nay-sayers about MI, but for the most part, except maybe for COM, .NET Interfaces are a way of doing the same thing without calling it MI.

Just my hap'orth,

Archimage
(Ann-Marie Ratcliffe)


[edited by - Archimage on May 12, 2004 2:22:23 AM]

This topic is closed to new replies.

Advertisement