Categories
C#

C#: When to use fields, get/set, properties, and/or methods

namespace TestCode {

    using System;

    /// <summary>When to use fields, getters, properties, and/or setters.</summary>
    /// <remarks>Totally open to suggestions to showcase wrong/right patterns.</remarks>
    public class WrongBetterRight {

        /// <summary>Bad.</summary>
        public class VersionA {

            /// <summary>Totally exposed public field. No protection.</summary>
            public Int32 ID;

            /// <summary>getter that 'does' something. Should be a method.</summary>
            public Int32 CalculateID => ( this.ID / 2 ) + ( this.ID / 2 );

            /// <summary>Okay, but still a getter.</summary>
            public Int32 GetID => this.ID;

            /// <summary>ctor.</summary>
            /// <param name="id"></param>
            public VersionA( Int32 id ) => this.ID = id;

            /// <summary>*poof* your app just blew up.</summary>
            /// <param name="newid"></param>
            public Boolean ChangeID( Int32 newid ) {
                this.ID = newid;

                return true;
            }

        }

        public class VersionB {

            /// <summary>Better than a public non-readonly field. Still vulnerable to a future change to property.</summary>
            public readonly Int32 ID;

            /// <summary>Only returns value. Okay.</summary>
            public Int32 GetID => this.ID;

            /// <summary>ctor. No checks yet.</summary>
            /// <param name="id"></param>
            public VersionB( Int32 id ) => this.ID = id;

            /// <summary>Contrived. 'Does' something, so a method is okay.</summary>
            /// <returns></returns>
            public Int32 CalculateID() => ( this.ID / 2 ) + ( this.ID / 2 );

            /// <summary>Prevents this method from changing ID. Which the compiler would prevent anyways. Not as easy to refactor (what 'value'??).</summary>
            /// <param name="newid"></param>
            /// <returns></returns>
            public Boolean ChangeID( Int32 newid ) => throw new InvalidOperationException( "value is not allowed to be changed." );

        }

        public class VersionC {

            /// <summary>Best way. Future proof. Property hides away field.</summary>
            public Int32 ID { get; }

            /// <summary>ctor. Checks incoming value.</summary>
            /// <param name="id"></param>
            public VersionC( Int32 id ) {
                this.ValidateValue( id );

                this.ID = id;
            }

            private void ValidateValue( Int32 id ) {
                ThrowIfValueTooLow();

                ThrowIfValueTooHigh();

                void ThrowIfValueTooLow() {
                    const Int32 minimumAllowedValue = 1;

                    if ( id < minimumAllowedValue ) {

                        //Exception message wording could better. But easy to refactor.
                        throw new ArgumentOutOfRangeException( nameof( id ), id, $"The value `{id}` is too low for {nameof( this.ID )}." );
                    }
                }

                void ThrowIfValueTooHigh() {
                    const Int32 maximumAllowedValue = 10;

                    if ( id > maximumAllowedValue ) {

                        //Exception message wording could better. But easy to refactor.
                        throw new ArgumentOutOfRangeException( nameof( id ), id, $"The value `{id}` is too high for {nameof( this.ID )}." );
                    }
                }
            }

            /// <summary>Future proof. Doesn't expose <see cref="ID" /> directly. Easy to refactor.</summary>
            /// <returns></returns>
            public Int32 CalculateID() => ( this.ID / 2 ) + ( this.ID / 2 );

            /// <summary>prevents this method from changing <see cref="ID" />. which the compiler would prevent anyways. but easier to refactor <see cref="ID" />.</summary>
            /// <param name="newid"></param>
            /// <returns></returns>
            public Boolean ChangeID( Int32 newid ) => throw new InvalidOperationException( $"{nameof( this.ID )} is not allowed to be changed." );

            /// <summary>Valid. Better than a plain getter? Debatable. This is more future proof though.</summary>
            public Int32 GetID() => this.ID;

        }

    }
}
Categories
C# description enum

C# Enum.Description() extension method

        /// 
/// Returns the text of the [Description("text")] attribute on an enum. Or null if not found.
///

///
///
[ CanBeNull ]
public static String Description( this Enum element ) {
var type = element.GetType();

var memberInfo = type.GetMember( element.ToString() );

if ( !memberInfo.Any() ) {
return null;
}
var attributes = memberInfo[ 0 ].GetCustomAttributes( typeof( DescriptionAttribute ), false );

return attributes.Any() ? ( attributes[ 0 ] as DescriptionAttribute )?.Description : null;
}
Categories
C# visual studio

My thoughts on Visual Studio 2012 RC

Visual Studio 2012.. All caps on the menu. REALLY? Why!?

Categories
C# enum random

Pick a Random Enum in C# (Better than my old post)

static T RandomEnum() {
           if ( typeof( T ).IsEnum ) {
                var names = Enum.GetNames( typeof( T ) );
                return ( T )Enum.Parse( typeof( T ), names[ threadsafeRandom.Value.Next( 0, names.Length ) ] );
            }
            return default( T );
}

static readonly ThreadLocal threadsafeRandom = new ThreadLocal( () => new Random( RandomSeed() ) );
Categories
C# programming

Programmers. Sigh.

Programmers.

Sigh.

You know those pesky ‘warnings’ that your build pukes up?

Yah… stop ignoring them.

You’re most likely doing whatever it is you intended on doing the wrong way.

/sigh

Categories
bad code C# dos hacking

Low Orbit Ion Cannon

I just checked out the source code from the LOIC (Wikipedia) project.

Wow.

As in.. “Wow, what immature dumbass wrote this C# code?” !

Horrible design and flaky as crap.
Good thing to know we are being ‘freed’ by ‘people’ with these ‘elite’ ‘skillz’.

Ugh, now I feel dirty.. fap fap fap.

Categories
C# duplicates

C#: Another HasDuplicates() for IEnumerable


.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: Consolas, “Courier New”, Courier, Monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

public static bool HasDuplicates_Version2( this IEnumerable sequence ) {
if ( null == sequence ) {
throw new ArgumentNullException( "sequence" );
}
var set = new HashSet();
return !sequence.All( set.Add );
}
Categories
C# duplicates

C#: HasDuplicates() extension for IEnumerable

Continuing on my previous post..

public static bool HasDuplicates( this IEnumerable sequence ) {
if ( null == sequence ) { throw new ArgumentNullException( "sequence" ); }
return sequence.Duplicates().Any();

 

}
Categories
C# duplicates

C#: IEnumerable get Duplicates (Select Non-Distinct with LINQ)

Saw this page: Raucous Random Ramblings: Select Non-Distinct with Linq!

[Updated 2012-06-12]

Not too shabby.. FWIW: the GetDuplicates() from the raucous random ramblings post returns all items it considers are duplicates.

This is different than my version, which only returns items after they are found in the list. I consider my version better because: if I existed and someone made a clone of me (i.e. ‘duplicated’), then I would not consider myself contained in the set of the duplicates. 🙂 But I can understand someone using both functions for different purposes.)

Here is my version for getting duplicates from an enumerable list.
Better? You try both and then let me know what your results are..

.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: Consolas, “Courier New”, Courier, Monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

/// 
///   Returns duplicate items found in the .
/// 
public static IEnumerable Duplicates( this IEnumerable sequence ) {
if ( null == sequence ) {
throw new ArgumentNullException( "sequence" );
}
var set = new HashSet();
return sequence.Where( item => !set.Add( item: item ) );
}

In the testing I slimmmed the two foreach down to “return results.SelectMany( @group => @group )” per Resharper’s suggestion.

Examples for the set of

    {1,2,3,4,5,6,7,8,9,6,4,2,2,4,6}
  • Duplicates() returns {6,4,2,4,4,6}
  • GetDuplicates() returns {2,2,2,4,4,4,6,6,6}

Speed tests!
I threw together a function timer with a massive UInt64[1048576] to check for duplicates.
Letting the tests run for a few minutes (over the same set of data)…

  • Duplicates() processes at 3338 units every millisecond.
  • GetDuplicates() processes at 1060 units every millisecond.

Remember: the test results are going to vary under different conditions, of course.
Ignoring the duplicate duplicates that both functions return with a .Distinct() did not make a noticeable timing impact.
Increasing the count of duplicates in the test data increased the speed of both function.
I do like the result set my function returns, and it does perform 3X faster than the raucous post..

Categories
C# java

Java vs C#

DateTime.Now is all I have to say.
http://rcm.amazon.com/e/cm?t=aibrain&o=1&p=8&l=bpl&asins=0672330768&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifrhttp://rcm.amazon.com/e/cm?t=aibrain&o=1&p=8&l=bpl&asins=0321356683&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifrhttp://rcm.amazon.com/e/cm?t=aibrain&o=1&p=8&l=bpl&asins=0132130807&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr