Agile Noob
Agile Noob

Reputation: 2335

unidentified syntax in domain object constructor

Can someone help me identify what the purpose of this unidentified syntax is. It is an extra little something in the constructor for this object. What I'm trying to figure out is what is the "< IdT >" at the end of the class declaration line? I think that this is something I would find useful, I just need to understand what it is why so many people seem to do this.

using BasicSample.Core.Utils;

namespace BasicSample.Core.Domain
{
    /// <summary>
    /// For a discussion of this object, see 
    /// http://devlicio.us/blogs/billy_mccafferty/archive/2007/04/25/using-equals-gethashcode-effectively.aspx
    /// </summary>
    public abstract class DomainObject<IdT>
    {
        /// <summary>
        /// ID may be of type string, int, custom type, etc.
        /// Setter is protected to allow unit tests to set this property via reflection and to allow 
        /// domain objects more flexibility in setting this for those objects with assigned IDs.
        /// </summary>
        public IdT ID {
            get { return id; }
            protected set { id = value; }
        }

Upvotes: 0

Views: 197

Answers (4)

tvanfosson
tvanfosson

Reputation: 532635

In this case it allows the ID property to take on various values without having to define a class for each ID property type. For example, ID could be int, or long, or Guid depending on the underlying data type in the database.

Upvotes: 1

gcores
gcores

Reputation: 12656

Read about Generics: MSDN

That is how you define a generic class. Hence calling

new DomainObject<string>(); 

would create a domain object with an Id of type string.

The way you define the ID must be an int.

The way it is defined the id can be any type you want.

Upvotes: 2

Agile Noob
Agile Noob

Reputation: 2335

right I'm somewhat aware of what generics are, have used Lists, delegates, etc. What I don't understand I guess is what effect putting "< dataType >" after a class declaration does, and why you would do it. If I were to declare this object I'd do the following:

Public class DomainObject { Public DomainObject(int ID) { this.ID = ID; } ....

Upvotes: 0

Jim Anderson
Jim Anderson

Reputation: 3622

From the C# spec:

A class type that is declared to take type parameters is called a generic class type. Struct, interface and delegate types can also be generic. When the generic class is used, type arguments must be provided for each of the type parameters

Upvotes: 1

Related Questions