New methods on existing extensions

Developer
May 28, 2008 at 10:16 PM
I'd like to add the following method to String extensions...

        public static string NotNullOrEmpty(this string instance, string name)
        {
            if (instance.IsNullOrEmpty())
                throw new ArgumentNullException(name);
            return instance;
        }

Usage...

    string s1 = null;
    var s2 = s1.NotNullOrEmpty("s1");

Similar to the Validation().NotNull("name") extension except takes into account the empty portion as well.  Maybe a better place to put it would be on ValidationExtensions like so...

        public static string NotNullOrEmpty(this ValidationExtensionPoint<string> extensionPoint, string name)
        {
            if (extensionPoint.ExtendedValue.IsNullOrEmpty())
            {
                throw new ArgumentNullException(name);
            }

            return extensionPoint.ExtendedValue;
        }

But StringExtensions made the most sense to me since it already has IsNullOrEmpty and others.

A couple of methods on SerializationExtensions...

        public static T Binary<T>(this SerializationExtensionPoint<T> extensionPoint, byte[] data)
        {
            using (var stream = new MemoryStream(data))
            {
                var serializer = new BinaryFormatter();
                return (T)serializer.Deserialize(stream);
            }
        }

        public static void Binary<T>(this SerializationExtensionPoint<T> extensionPoint, Stream output)
        {
            var serializer = new BinaryFormatter();
            serializer.Serialize(output, extensionPoint.ExtendedValue);
            output.Flush();
        }

Those are fairly self-explanatory.  One thing I think that would make more since would be to name them FromBinary and ToBinary.  But I followed the convention in the file already.

Thoughts on these additions?

Coordinator
May 29, 2008 at 3:14 AM

NotNullOrEmpty should extend ValidationExtensionPoint<string>. Probably in a StringValidationExtensions class.

I'm fine with the SerializationExtensions and agree that we might have to rename with From/To at some point. I'd suggest we push the rename until we have more feedback though.

Developer
May 29, 2008 at 9:40 PM
OK...changes have been made.  I'll check them in a bit.