tags:

views:

97

answers:

2

Hey guys,

I'm having trouble grasping generic methods.

I have two classes that are generated (they are exactly the same, but i can't reactor the code to use the same class object).

here are the classes:

public class1 : SoapHttpClientProtocol {
    public partial class notificationsResponse {

        private ResponseType[] responsesField;

        private bool ackField;

        /// <remarks/>
        public ResponseType[] Responses {
            get {
                return this.responsesField;
            }
            set {
                this.responsesField = value;
            }
        }

        /// <remarks/>
        public bool Ack {
            get {
                return this.ackField;
            }
            set {
                this.ackField = value;
            }
        }
    }
}

public class2 : SoapHttpClientProtocol {
    public partial class notificationsResponse {

        private ResponseType[] responsesField;

        private bool ackField;

        /// <remarks/>
        public ResponseType[] Responses {
            get {
                return this.responsesField;
            }
            set {
                this.responsesField = value;
            }
        }

        /// <remarks/>
        public bool Ack {
            get {
                return this.ackField;
            }
            set {
                this.ackField = value;
            }
        }
    }
}

as you can see class1 and class2 are the same; and since they are inline classes i have to have duplication.

With that aside, I'm trying to call an update method with these class types as a parameter:

    private void UpdateMessageResponses<T>(T results)
    {
        T responses = (T)results;

        foreach (var accts in results.Responses)
        {
            int row = GetRowIdByAccountId(accts.ObjectId);
            if (row != -1)
            {
                TestResultsGrid["Status", row].Value = String.Format("{0} {1} - {2} - {3}", accts.ResponseDate, accts.ObjectType, accts.Message, accts.ObjectId);
            }
        }
    }

how can i cast the results properly so that i can access the results properties?

+1  A: 

I may be wrong, but I don't think you can do that purely with generics. The only way you could would be to have a restriction to the generic type parameter, but since the members that you want to access are not declared in a base class that is common for your two classes that option is ruled out, unfortunately.

Fredrik Mörk
+2  A: 

You need to define an interface for the Responses property, and then specify that T must implement that interface (and that your classes do implement the interface).

Ganesh Sittampalam
Thanks, Interface worked; Dunno why i forgot about those ;)
Michael G