473,888 Members | 1,437 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

CA1000: Why shouldn't I declare static members on generic types?

5 New Member
I've written an abstract base type which uses generics to provide XML serialization and deserialization methods for use by its derived types, but I'm seemingly unable to write it in a way which completely satisfies FxCop code analysis. Here is the simplest form of the base class which reproduces the problem:

Expand|Select|Wrap|Line Numbers
  1. public abstract class XmlSerializableItem<T>
  2. {
  3.     public string ToXml()
  4.     {
  5.         XmlSerializer xs = new XmlSerializer( this.GetType() );
  6.         TextWriter xw 
  7.             = new StringWriter( CultureInfo.InvariantCulture );
  8.         xs.Serialize( xw, this );
  9.         return Convert.ToString( xw, CultureInfo.InvariantCulture );
  10.     }
  12.     [SuppressMessage("Microsoft.Design", 
  13.                     "CA1000:DoNotDeclareStaticMembersOnGenericTypes")]
  14.     public static T FromXml( string xml )
  15.     {
  16.         XmlSerializer xs = new XmlSerializer( typeof( T ) );
  17.         TextReader tr = new StringReader( xml );
  18.         return (T) xs.Deserialize( tr );
  19.     }
  20. }
The derived type would look something like

Expand|Select|Wrap|Line Numbers
  1. public class MyDerived : XmlSerializableItem<MyDerived>
  2. {
  3.     /* add some properties etc */
  4. }
and it would be used like this

Expand|Select|Wrap|Line Numbers
  1. MyDerived d1 = new MyDerived(); // assume a suitable constructor has been implemented
  2. string xml = d1.ToXml();
  3. MyDerived d2 = MyDerived.FromXml( xml );
and after executing this, we'd have two instances of MyDerived, both with the same property values.

The reason the base type needs to be generic is so that I can use the type parameter T as the return type of the FromXml method.

The problem is that the FromXml method throws a FxCop warning CA1000:DoNotDec lareStaticMembe rsOnGenericType s. Microsoft seem to be quite emphatic that warning CA1000 should not be suppressed although I'm not sure I agree in this case. Their reason is

// Static method in a generic type.
GenericType<int >.StaticMethod( );

// Generic instance method that does not support inference.
someObject.Gene ricMethod<int>( );

Generally, both of the prior declarations should be avoided so that the type argument does not have to be specified when the member is called. This results in a syntax for calling members in generics that is no different from the syntax for non-generics.
Except in this case the type parameter is supplied in the derived type's class declaration and does not need to be provided when the derived type is used - the XmlSerializable Item class is effectively hidden from consumers of the derived type.

If I follow Microsoft's suggestion and change FromXml from a static method to an instance method then the derived type becomes, if anything, more difficult to use:

Expand|Select|Wrap|Line Numbers
  1. MyDerived d1 = new MyDerived(); // assume a suitable constructor has been implemented
  2. string xml = MyDerived.ToXml();
  3. MyDerived d2 = new MyDerived();
  4. MyDerived d2 = d2.FromXml( xml );
I need an extra line of code, instantiating an instance of MyDerived, whose value is never used because that instance is only used to make the FromXml method available so that I can instantiate the instance that I actually want, from the XML string. This strikes me as a bit silly.

Maybe I'm missing something, and there's another way of providing this deserialization functionality in a base type without violating any FxCop rules. Or maybe Microsoft have got it wrong and this rule shouldn't apply to static members on abstract base types. Any thoughts on this subject much appreciated...


Aug 19 '09 #1
0 3005

Sign in to post your reply or Sign up for a free account.

Similar topics

by: Erik Arner | last post by:
Hi, I really need some help here. After upgrading to g++ 3.4 I have run into all sorts of troubles that I'm sure depends on my lack of proper understanding of C++. I would now like to get it right once and for all, if possible. Most severe is the problem illustrated by the code below. It's based on the "pluggable factory pattern" described in http://www.adtmag.com/joop/crarticle.asp?ID=1520
by: Sharon | last post by:
I’m trying to build a generic Publisher-Subscriber that will work over the net, so I’m using the Remoting. I wish that the subscriber user will be notify about the messages sent by the remote publisher, so I used delegate that the user will be able to set on it his own function for that purpuse. The trouble is that this delegate must not be static because there may be many subscribers, and each subscriber may have different...
by: Kevin Prichard | last post by:
Hi all, I've recently been following the object-oriented techiques discussed here and have been testing them for use in a web application. There is problem that I'd like to discuss with you experts. I would like to produce Javascript classes that can be "subclassed" with certain behaviors defined at subclass time. There are plenty of ways to do this through prototyping and other techniques, but these behaviors need to be static and...
by: Ole Nielsby | last post by:
I'm puzzled at how static fields intersect with generics, as the following snippet illustrates. namespace MonkeyParty { abstract class Fruit { } class Apple : Fruit { } class Pear : Fruit { }
by: Ole Nielsby | last post by:
Here comes a generic class with a static property. Let's say they are exotic singleton pets. abstract class Pet {...} abstract class SharedPet<T>: Pet where T: SharedPet<T>, new() { private static T singleton = new T();
by: Steve Richter | last post by:
in a generic class, can I code the class so that I can call a static method of the generic class T? In the ConvertFrom method of the generic TypeConvert class I want to write, I have a call to the static Parse method of the conversion class. if (InValue is string) return T.Parse((string)InValue); else return base.ConvertFrom(context, culture, InValue);
by: Ben Voigt [C++ MVP] | last post by:
I'm trying to construct a compelling example of the need for a language feature, with full support for generics, to introduce all static members and nested classes of another type into the current name search scope. i.e. a very simple application would be class ManyComputations { calling System.Math;
by: Filip Zawada | last post by:
Hi, I've encountered a rather interesting language problem. Suppose I've got following types: //class providing usefull static methods public class GoodBase<T> { public static void Met(){}; }
by: Bill McCormick | last post by:
Hi C# programmers, I'd like to be able to call a static function or property and have it return a generic list. The compiler indicates that "static types cannot be used as generic arguments", so I'm looking for the correct way to do this and/or other alternatives. The static function should make some DB query, build some objects foreach record and populate a List<T>. In the end, I'd like to be able to use it like this:
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.