.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

Better way to deal with generics?

Posted By:      Posted Date: October 19, 2010    Points: 0   Category :.NET Framework

I have two collections in my program: List<BaseClass> and List<DerivedClass>. I often need to cycle through both collections. It's so tedious to write 2 cycles every time:

foreach (BaseClass obj in baseClassList)
   ; //Do something

foreach (DerivedClass obj in derivedClassList)
   ; //Do exactly the same thing

I thought, since the objects in the second collection are of a derived class, and not just completely unrelated class, there should be some more elegant way to write this piece of code. Also, I'm concerned with performance, of course: I guess creating a 3rd list and copying all the objects from the 1st and 2nd list into the 3rd list doesn't sound like a good idea. Please, help me!

View Complete Post

More Related Resource Links

TreeSelector : playing with generics and type inference

create a generic way to define a selection starting from a tree of objects, the most simpler way as possible.

Let's start with the beginning...
Here is a very simple little interface defining a node of the tree, basically, a value and the references to the child nodes.

Advanced Basics: Reflection and Generics


This month Advanced Basics flaunts the power of generics and reflection and shows how you get more flexible and efficient development by combining the two.

Ken Getz

MSDN Magazine January 2008

Netting C++: Mapping Templates to Generics


In this installment, Stanley Lippman continues to port his ISO-C++ Text Query Language application to the Microsoft .NET Framework and C++/CLI.

Stanley Lippman

MSDN Magazine April 2007

Pure C++: How Templates and Generics Work Together


I'm closing out this series of columns on generic programming in the Microsoft® . NET Framework by showing how templates and generics do and do not work together, and pointing out a pitfall with the current implementation of templates under Visual C++® 2005.

Stanley B. Lippman

MSDN Magazine April 2006

.NET Column: Introducing Generics in the CLR


Generics are an extension of the CLR type system that allow developers to define types for which certain details are left unspecified. These details are specified when the code is referenced by consumer code, making for enhanced flexibility. Jason Clark explains how.

Jason Clark

MSDN Magazine Visual Studio 2005 Guided Tour 2006

Pure C++: CLR Generics Versus C++ Templates


Visual Studio® 2005 brings the type parameter model of generic programming to the Microsoft® . NET Framework. C++/CLI supports two type parameter mechanisms-common language runtime (CLR) generics and C++ templates.

Stanley B. Lippman

MSDN Magazine June 2005

How to deal with NULL values in a SQL table


 Hi all

In order to add/update/delete data from a table I build 2 classes: 1 class containing all the table fields and another class with methods to add/insert/update/delete records. I am learning how to avoid errors when your table must use SQL NULL values. One error is when I call my UPDATE method (see below):

  public void UpdateItem(OcItemConstraintDetails item)
  SqlConnection con = new SqlConnection(connectionString);
  SqlCommand cmd = new SqlCommand("ItemConstraints_Update", con);
  cmd.CommandType = CommandType.StoredProcedure;

  cmd.Parameters.Add(new SqlParameter("@itemConstraintId", SqlDbType.Int, 4));
  cmd.Parameters["@itemConstraintId"].Value = item.ItemConstraintId;

  cmd.Parameters.Add(new SqlParameter("@path", SqlDbType.NVarChar, 150));
  cmd.Parameters["@path"].Value = item.Path;

if you watch the SQL profiler trace you will see that I am passing a value of 'default' ;so that causes me problems.

exec ItemConstraints_Update @itemConstraintId=1,@path=default

With that said, what are the best practices when your SQL table accepts NULL values and when:
- you are passing an empty value to your stored procedure;

How best to deal with a static C Library which is currently 32-bit?

My application is a mix of a number of different executables and DLL's that are both managed and unmanaged code.  One thing everything has in common is the licensing library which is written in C as a static library.  The managed code is gaining access to this static C library via a C++ CLI assembly which links in the library.  I would like to start offering the managed code as a 64-bit app, but I don't know exactly how to overcome the issue with the static C library and the C++ CLI assembly that consumes it...Assuming I port the static C library over so that there is also a 64-bit version, is there any way I can keep the C++ CLI code bit agnostic and link in both the 32-bit and 64-bit, allowing the Windows loader to use the correct one based on the machine it is running on?  If not, how does one go about telling the C++ CLI code to use the 32-bit library when compiling the C++ CLI to target a 32-bit process and 64-bit library when targetting a 64-bit process?Sam

Serialization and generics : problem with xmlinclude

Hello everyone. I've got a hierarchy of class like this: [Serializable] [xmlinclude(DiscreteDomain)] public abstract class Domain { } [Serializable] [xmlinclude(DiscreteDomain<>)] public abstract class DiscreteDomain : Domain { } [Serializable] public sealed class DiscreteDomain<T> : DiscreteDomain { } I can't serialize an object of type DiscreteDomain<T> because xmlinclude can't be used with a generics like DiscreteDomain<> (a type must be specified but i can't).   How can I serialize this type of object ?   Thx, JP

Querystring format to deal with Ampersand(&)

Hi, I use the following string format to navigate between webpages: String.Format(Eval("Hyper") + "?BUSINESSSTREAM={0}&Dealer={1}&LeadID={2}&Companyid={3}&SalesPerson={4}",  Eval("BusinessStream"), Eval("Dealer"),Eval("leadId"),Eval("CompanyID"),Eval("SalesPerson")) However the companyid is a text string and the company may have an "&" in it which I know will truncate the string. I have seen that this can be overcome by using  "UrlEncode" (http://forums.asp.net/p/1206489/2113465.aspx#2113465) However I cant solve the syntax. Any suggestions appeciated. Regards Colin    

Linq to SQL and Generics

I'm using something like the following code (programatically mapped) to save on linq to sql:     SaveEmployee(Employee employee)     {         MyCompanyContext context = new MyCompanyContext();         context.Employees.InsertOnSubmit(employee);         context.SubmitChanges();     } Now I'm trying to implement a new architecture, using CRUD and generic methods, like:     Save(T entity)     {             MyCompanyContext context = new MyCompanyContext();             //context.Employees.InsertOnSubmit(employee);             //context.SubmitChanges();     } But I'm having a hard time to code the two commented lines. Any tip? Best regards, André

Generics with Interface constraint from WCF.

Hello Not sure this is possible, but there might be a smart person out there who can answer it. Heck, maybe its simple :) I have a class that consumes an WCF service. That class contains the following generic method:   private void BuildTree<T, U>(T tree, U rootNode, ref List<U> listToBeBuilt) where T : ITreeDefinition, IEnumerable<T> where U : ITreeDefinition { ... }  Basically, it builds a tree based on generic data etc. However, it can't work without ITreeDefinition:   public interface ITreeDefinition { string GetRoot { get; set; } string GetChild { get; set; } }    This interface is contained in the WCF service, and used like so:   [DataContract] [KnownType(typeof(ITreeDefinition))] public class CaseStructureInfo : ITreeDefinition { #region OtherCode ... #endregion // Defines what properties to use to build a treetable. [DataMember] public string GetRoot { get { return SagsNr; } set { SagsNr = value; } } [DataMember] public string GetChild { get { return Hovedsag; } set { Hovedsag = value; } } }    The problem: The constraint "ITreeDefinition" is unknown to the generic method, because it is only visible in the WCF service. Can anyone help me out with this? Ps.  For the sake of understanding, here is the rest of the generic method... it is recursive, so

What is the deal with ASP.NET Visual C# and Visual Basic

Hey everyone,This is my first post here, and it looks like a great community, with lots of generous help available!I am just delving into ASP.NET and the .NET framework and it appears to be a little daunting at first.What is the deal with having to choose a language for ASP.NET?Isn't ASP.NET already a web server language itself?Can you also choose JavaScript like you could in Classic-ASP?Isn't C# more for offline development anyway?I'm just trying to get a feel here, because this concept appears to be rather new to me! Any help is greatly appreciated!Thanks!!

How to: Deal with UniqueIdentifiers, casting it to Guid in DAL

HelloMy users table has a column which is a unique identifier (basically this has FK relationship with aspnet_users table, of membership) Now I have an AppUser class which maps to my users tableuserid        intuser_aspnet_id  guid In my DAL, I am retreiving a user from the db an want to populate my appUser obj. How do i Convert value retreived to GuidappUsr.UserID = Convert.ToInt32(reader["user_id"]);appUsr.AspNetUserID =  reader["aspnet_user_id"];(There is no convert.ToGuid)How can this be done?appUsr.UserID = Convert.ToInt32(reader["user_id"]);                 appUsr.AspNetUserID = (Guid)reader["aspnet_user_id"];

Limitations of Generics

1. Can anyone explain me the basic disadvantage og generics and delegates? 2. Also i would like to know the the basic reason why generics were introduces apart from TYPE SAFETY???  3. What is the difference between Error and Exception ? 4. What is the difference between shadowing and overriding? Note: Request you to please don't send any links and  please explain with examples. Any help APPRECIATED.
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend