ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

Or (with explicit reference for strings)

Returns the object if it's not null or the first object which is not null, With explicit reference for strings

Source

/// <summary>
		///Returns the object if it's not null or the first object which is not null.
		/// Original Idea: Weidling C
		/// </summary>
		/// <typeparam name="T">Type of origination</typeparam>
		/// <param name="this">current object to be OR'ed</param>
		/// <param name="oValues">Array of type <c>T</c> for the rest of the list</param>
		/// <returns><see cref=""/> Item - or if null/empty move to next item chech and return &lt;-- Looping trought all items in oValues if all are empty, returnds default <see cref="T"/>value</returns>
		public static T Or<T>(this T @this, params T[] oValues)
		{
			foreach (var item in oValues)
			{
				if (@this is string)
				{
					if (string.IsNullOrWhiteSpace(@this.ToString()) == false)
					{
						return (@this);
					}
				}
				else
				{
					// ReSharper disable once CompareNonConstrainedGenericWithNull
					if (item != null)
					{
						return (item);
					}
				}
			}

			return default(T);
		}

Example

string s = GetValue(); // s == null
Console.WriteLine(s.Or("value not found")):

Author: D.Magician

Submitted on: 10 dec. 2014

Language: C#

Type: System.Object<T>

Views: 3515