System.Type.IsEquivalentTo(System.Type)

Here are the examples of the csharp api System.Type.IsEquivalentTo(System.Type) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

54 Examples 7

19 Source : ConversionHelper.cs
with MIT License
from abdullin

private static bool AreEquivalentTypes(Type t1, Type t2)
		{
			return t1 == t2 || t1.IsEquivalentTo(t2);
		}

19 Source : TradeAnnotationsViewModel.cs
with MIT License
from ABTSoftware

private void SetAnnotationTypeExecute(Type type)
        {
            if (IsAnnotationCreationEnable && type.IsEquivalentTo(AnnotationType))
            {
                IsAnnotationCreationEnable = false;
                AnnotationType = null;
            }
            else
            {
                IsAnnotationCreationEnable = true;
                AnnotationType = type;
            }
        }

19 Source : Util.cs
with MIT License
from albahari

public static bool AreEquivalent (Type t1, Type t2)
		{
			if (t1 != null)
			{
				return t1.IsEquivalentTo (t2);
			}
			return false;
		}

19 Source : ClayMetaObject.cs
with MIT License
from bleroy

private Expression GetLimitedSelf() {
            if (Expression.Type == LimitType || Expression.Type.IsEquivalentTo(LimitType)) {
                return Expression;
            }
            return Expression.Convert(Expression, LimitType);
        }

19 Source : AssemblyScanner.cs
with Apache License 2.0
from buehler

public IreplacedemblyScanner Addreplacedembly(replacedembly replacedembly)
        {
            var types = replacedembly.GetTypes()
                .Where(t => (t.Attributes & TypeAttributes.Abstract) == 0);

            var registrationMethods = _registrationDefinitions.Join(
                    types,
                    _ => 1,
                    _ => 1,
                    (registrationDefinition, type) =>
                        new { RegistrationDefinition = registrationDefinition, ComponentType = type })
                .Where(
                    t => t.ComponentType.GetInterfaces()
                        .Any(
                            i => (i.IsConstructedGenericType &&
                                  i.GetGenericTypeDefinition().IsEquivalentTo(t.RegistrationDefinition.Type)) ||
                                 (t.RegistrationDefinition.Type.IsConstructedGenericType &&
                                  i.IsEquivalentTo(t.RegistrationDefinition.Type))))
                .Select(
                    t => t.RegistrationDefinition.RegistrationMethod.MakeGenericMethod(t.ComponentType));

            foreach (var method in registrationMethods)
            {
                method.Invoke(null, new object[] { _operatorBuilder });
            }

            return this;
        }

19 Source : OperatorBuilderExtensions.cs
with Apache License 2.0
from buehler

public static IOperatorBuilder AddFinalizer<TImplementation>(this IOperatorBuilder builder)
            where TImplementation : clreplaced
        {
            var enreplacedyTypes = typeof(TImplementation).GetInterfaces()
                .Where(
                    t =>
                        t.IsConstructedGenericType &&
                        t.GetGenericTypeDefinition().IsEquivalentTo(typeof(IResourceFinalizer<>)))
                .Select(i => i.GenericTypeArguments[0]);

            var genericRegistrationMethod = builder
                .GetType()
                .GetMethods()
                .Single(m => m.Name == nameof(AddFinalizer) && m.GetGenericArguments().Length == 2);

            foreach (var enreplacedyType in enreplacedyTypes)
            {
                var registrationMethod =
                    genericRegistrationMethod.MakeGenericMethod(typeof(TImplementation), enreplacedyType);
                registrationMethod.Invoke(builder, Array.Empty<object>());
            }

            return builder;
        }

19 Source : OperatorBuilderExtensions.cs
with Apache License 2.0
from buehler

public static IOperatorBuilder AddController<TImplementation>(this IOperatorBuilder builder)
            where TImplementation : clreplaced
        {
            var enreplacedyTypes = typeof(TImplementation).GetInterfaces()
                .Where(
                    t =>
                        t.IsConstructedGenericType &&
                        t.GetGenericTypeDefinition().IsEquivalentTo(typeof(IResourceController<>)))
                .Select(i => i.GenericTypeArguments[0]);

            var genericRegistrationMethod = builder
                .GetType()
                .GetMethods()
                .Single(m => m.Name == nameof(AddController) && m.GetGenericArguments().Length == 2);

            foreach (var enreplacedyType in enreplacedyTypes)
            {
                var registrationMethod =
                    genericRegistrationMethod.MakeGenericMethod(typeof(TImplementation), enreplacedyType);
                registrationMethod.Invoke(builder, Array.Empty<object>());
            }

            return builder;
        }

19 Source : OperatorBuilderExtensions.cs
with Apache License 2.0
from buehler

public static IOperatorBuilder AddValidationWebhook<TImplementation>(this IOperatorBuilder builder)
            where TImplementation : clreplaced
        {
            var enreplacedyTypes = typeof(TImplementation).GetInterfaces()
                .Where(
                    t =>
                        t.IsConstructedGenericType &&
                        t.GetGenericTypeDefinition().IsEquivalentTo(typeof(IValidationWebhook<>)))
                .Select(i => i.GenericTypeArguments[0]);

            var genericRegistrationMethod = builder
                .GetType()
                .GetMethods()
                .Single(m => m.Name == nameof(AddValidationWebhook) && m.GetGenericArguments().Length == 2);

            foreach (var enreplacedyType in enreplacedyTypes)
            {
                var registrationMethod =
                    genericRegistrationMethod.MakeGenericMethod(typeof(TImplementation), enreplacedyType);
                registrationMethod.Invoke(builder, Array.Empty<object>());
            }

            return builder;
        }

19 Source : OperatorBuilderExtensions.cs
with Apache License 2.0
from buehler

public static IOperatorBuilder AddMutationWebhook<TImplementation>(this IOperatorBuilder builder)
            where TImplementation : clreplaced
        {
            var enreplacedyTypes = typeof(TImplementation).GetInterfaces()
                .Where(
                    t =>
                        t.IsConstructedGenericType &&
                        t.GetGenericTypeDefinition().IsEquivalentTo(typeof(IMutationWebhook<>)))
                .Select(i => i.GenericTypeArguments[0]);

            var genericRegistrationMethod = builder
                .GetType()
                .GetMethods()
                .Single(m => m.Name == nameof(AddMutationWebhook) && m.GetGenericArguments().Length == 2);

            foreach (var enreplacedyType in enreplacedyTypes)
            {
                var registrationMethod =
                    genericRegistrationMethod.MakeGenericMethod(typeof(TImplementation), enreplacedyType);
                registrationMethod.Invoke(builder, Array.Empty<object>());
            }

            return builder;
        }

19 Source : ProjectElement.cs
with MIT License
from enricosada

public virtual void CopyFrom(ProjectElement element)
        {
            ErrorUtilities.VerifyThrowArgumentNull(element, "element");
            ErrorUtilities.VerifyThrowArgument(this.GetType().IsEquivalentTo(element.GetType()), "element");

            if (this == element)
            {
                return;
            }

            // Remove all the current attributes and textual content.
            this.XmlElement.RemoveAllAttributes();
            if (this.XmlElement.ChildNodes.Count == 1 && this.XmlElement.FirstChild.NodeType == XmlNodeType.Text)
            {
                this.XmlElement.RemoveChild(this.XmlElement.FirstChild);
            }

            // Ensure the element name itself matches.
            this.ReplaceElement(XmlUtilities.RenameXmlElement(this.XmlElement, element.XmlElement.Name, XmlElement.NamespaceURI));

            // Copy over the attributes from the template element.
            foreach (XmlAttribute attribute in element.XmlElement.Attributes)
            {
                if (ShouldCloneXmlAttribute(attribute))
                {
                    this.XmlElement.SetAttribute(attribute.LocalName, attribute.NamespaceURI, attribute.Value);
                }
            }

            // If this element has pure text content, copy that over.
            if (element.XmlElement.ChildNodes.Count == 1 && element.XmlElement.FirstChild.NodeType == XmlNodeType.Text)
            {
                this.XmlElement.AppendChild(this.XmlElement.OwnerDoreplacedent.CreateTextNode(element.XmlElement.FirstChild.Value));
            }

            this._expressedAsAttribute = element._expressedAsAttribute;

            this.MarkDirty("CopyFrom", null);
        }

19 Source : ProjectElement.cs
with MIT License
from enricosada

protected internal virtual ProjectElement Clone(ProjectRootElement factory)
        {
            var clone = this.CreateNewInstance(factory);
            if (!clone.GetType().IsEquivalentTo(this.GetType()))
            {
                ErrorUtilities.ThrowInternalError("{0}.Clone() returned an instance of type {1}.", this.GetType().Name, clone.GetType().Name);
            }

            clone.CopyFrom(this);
            return clone;
        }

19 Source : ProjectExtensionsElement.cs
with MIT License
from enricosada

public override void CopyFrom(ProjectElement element)
        {
            ErrorUtilities.VerifyThrowArgumentNull(element, "element");
            ErrorUtilities.VerifyThrowArgument(this.GetType().IsEquivalentTo(element.GetType()), "element");

            if (this == element)
            {
                return;
            }

            this.Label = element.Label;

            var other = (ProjectExtensionsElement)element;
            this.Content = other.Content;

            this.MarkDirty("CopyFrom", null);
        }

19 Source : ProjectElementContainer.cs
with MIT License
from enricosada

public virtual void DeepCopyFrom(ProjectElementContainer element)
        {
            ErrorUtilities.VerifyThrowArgumentNull(element, "element");
            ErrorUtilities.VerifyThrowArgument(this.GetType().IsEquivalentTo(element.GetType()), "element");

            if (this == element)
            {
                return;
            }

            this.RemoveAllChildren();
            this.CopyFrom(element);

            foreach (var child in element.Children)
            {
                var childContainer = child as ProjectElementContainer;
                if (childContainer != null)
                {
                    childContainer.DeepClone(this.ContainingProject, this);
                }
                else
                {
                    this.AppendChild(child.Clone(this.ContainingProject));
                }
            }
        }

19 Source : EmitExtensions.cs
with MIT License
from fs7744

public static void EmitConvertTo(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked = true)
        {
            if (typeFrom.IsEquivalentTo(typeTo))
            {
                return;
            }

            var typeFromInfo = typeFrom.GetTypeInfo();
            var typeToInfo = typeTo.GetTypeInfo();

            var nnExprType = typeFromInfo.GetNonNullableType();
            var nnType = typeToInfo.GetNonNullableType();

            if (typeFromInfo.IsInterface ||
              typeToInfo.IsInterface ||
               typeFrom == typeof(object) ||
               typeTo == typeof(object) ||
               typeFrom == typeof(Enum) ||
               typeFrom == typeof(ValueType) ||
               typeFromInfo.IsLegalExplicitVariantDelegateConversion(typeToInfo))
            {
                il.EmitCastTo(typeFromInfo, typeToInfo);
            }
            else if (typeFromInfo.IsNullableType() || typeToInfo.IsNullableType())
            {
                il.EmitNullableConversion(typeFromInfo, typeToInfo, isChecked);
            }
            else if (!(typeFromInfo.IsConvertible() && typeToInfo.IsConvertible()) // primitive runtime conversion
                     &&
                     (nnExprType.GetTypeInfo().IsreplacedignableFrom(nnType) || // down cast
                     nnType.GetTypeInfo().IsreplacedignableFrom(nnExprType))) // up cast
            {
                il.EmitCastTo(typeFromInfo, typeToInfo);
            }
            else if (typeFromInfo.IsArray && typeToInfo.IsArray)
            {
                il.EmitCastTo(typeFromInfo, typeToInfo);
            }
            else
            {
                il.EmitNumericConversion(typeFromInfo, typeToInfo, isChecked);
            }
        }

19 Source : TypeExtenions.cs
with MIT License
from fs7744

public static bool AreEquivalent(TypeInfo t1, TypeInfo t2) => t1 == t2
            || t1.IsEquivalentTo(t2.AsType());

19 Source : TransactionRider.cs
with Apache License 2.0
from horse-framework

private IServerTransactionEndpoint ResolveAndCreateEndpoint(ServerTransactionContainer container, string fullname, string parameter)
		{
			Type endpointType = ResolveType(fullname);

			if (endpointType == null)
				throw new Exception($"Endpoint Type type not found: {fullname}");

			ConstructorInfo[] ctors = endpointType.GetConstructors()
												  .OrderByDescending(x => x.GetParameters().Length)
												  .ToArray();

			ConstructorInfo constructor = null;
			object[] parameters = null;

			foreach (ConstructorInfo ctor in ctors)
			{
				ParameterInfo[] parameterInfos = ctor.GetParameters();
				parameters = new object[parameterInfos.Length];
				bool skip = false;

				for (int i = 0; i < parameterInfos.Length; i++)
				{
					ParameterInfo parameterInfo = parameterInfos[i];

					if (parameterInfo.ParameterType.IsEquivalentTo(typeof(QueueRider)))
						parameters[i] = Rider.Queue;

					else if (parameterInfo.ParameterType.IsEquivalentTo(typeof(DirectRider)))
						parameters[i] = Rider.Direct;

					else if (parameterInfo.ParameterType.IsEquivalentTo(typeof(ChannelRider)))
						parameters[i] = Rider.Channel;

					else if (parameterInfo.ParameterType.IsEquivalentTo(typeof(RouterRider)))
						parameters[i] = Rider.Router;

					else if (parameterInfo.ParameterType.IsEquivalentTo(typeof(HorseRider)))
						parameters[i] = Rider;

					else if (parameterInfo.ParameterType.IsEquivalentTo(typeof(ServerTransactionContainer)))
						parameters[i] = container;

					else if (parameterInfo.ParameterType.IsEquivalentTo(typeof(string)))
						parameters[i] = parameter;

					else
					{
						skip = true;
						break;
					}
				}

				if (skip)
					continue;

				constructor = ctor;
				break;
			}

			if (constructor == null)
				throw new Exception($"No suitable constructor found for endpoint: {fullname}");

			IServerTransactionEndpoint endpoint = constructor.Invoke(parameters) as IServerTransactionEndpoint;

			if (endpoint == null)
				throw new Exception($"Endpoint creation failed: {fullname}");

			return endpoint;
		}

19 Source : ServerSettings.cs
with GNU General Public License v3.0
from jweigelt

public static ServerSettings FromSettingsFile(AdminCore core, string path)
        {
            ServerSettings settings = new ServerSettings();
            string file = null;
            string fileName = path + FILE_NAME;

            if (!core.Files.FileExists(fileName))
            {
                return settings;
            }

            try
            {
                file = core.Files.ReadFileText(fileName);
                Logger.Log(LogLevel.Verbose, "Server settings saved.");
            }
            catch (Exception e)
            {
                Logger.Log(LogLevel.Error, "Failed to read to file {0} ({1})", fileName, e.ToString());
                throw e;
            }

            file = file.Replace("\r\n", "\n");
            string[] rows = file.Split('\n');
            PropertyInfo[] props = typeof(ServerSettings).GetProperties();

            foreach (string r in rows)
            {
                if (r.Length < 1) continue;
                string[] dat = r.Split(' ');

                bool found = false;
                string settingName = dat[0].Replace("/", "").ToLower();


                foreach (PropertyInfo p in props)
                {

                    ConfigSection[] attr = (ConfigSection[])p.GetCustomAttributes(typeof(ConfigSection), false);

                    if (p.Name.ToLower().Equals(settingName) ||
                        (attr.Length > 0 && attr[0].YesNoBool && ("no" + p.Name).ToLower().Equals(settingName)))
                    {
                        found = true;
                        if (p.PropertyType.IsEquivalentTo(typeof(bool)))
                        {
                            //some params like /splitudate use different commands to indicate their status
                            //(in this case /splitupdate & /nosplitupdate)
                            if (attr.Length > 0 && attr[0].YesNoBool)
                                p.SetValue(settings, !(settingName.StartsWith("no")));
                            else
                                p.SetValue(settings, (dat.Length > 1 && dat[1].Equals("1")));
                            continue;
                        }

                        if (dat.Length < 2)
                        {
                            Logger.Log(LogLevel.Warning, "Invalid server setting '{0}'. No value specified - skipping.", r);
                            continue;
                        }

                        if (p.PropertyType.IsEquivalentTo(typeof(ushort)))
                        {
                            if (!ushort.TryParse(dat[1], out ushort s))
                            {
                                Logger.Log(LogLevel.Warning, "Invalid server setting '{0}'. Expecting valid integer - skipping.", r);
                                break;
                            }
                            p.SetValue(settings, s);
                        }
                        else if (p.PropertyType.IsEquivalentTo(typeof(int)))
                        {
                            if (!int.TryParse(dat[1], out int i))
                            {
                                Logger.Log(LogLevel.Warning, "Invalid server setting '{0}'. Expecting valid integer - skipping.", r);
                                break;
                            }
                            p.SetValue(settings, i);
                        }
                        else if (p.PropertyType.IsEquivalentTo(typeof(string)))
                        {
                            string val = "";
                            int idx_start = 0, idx_stop = 0;

                            if ((idx_start = r.IndexOf('"')) > 0)
                            {
                                if ((idx_stop = r.IndexOf('"', ++idx_start)) < 0)
                                {
                                    Logger.Log(LogLevel.Warning, "Invalid server setting '{0}'. Expected closing \" - skipping.", r);
                                    break;
                                }
                                val = r.Substring(idx_start, idx_stop - idx_start);
                            }
                            else
                            {
                                val = dat[1];
                            }

                            p.SetValue(settings, val);
                        }
                    }
                }
                if (!found)
                {
                    Logger.Log(LogLevel.Warning, "Unknown server setting '{0}' - ignoring it.", r);
                }
            }
            return settings;
        }

19 Source : ServerSettings.cs
with GNU General Public License v3.0
from jweigelt

public void WriteToFile(AdminCore core)
        {
            string file = "";
            string fileName = core.Server.ServerPath + FILE_NAME;

            PropertyInfo[] props = typeof(ServerSettings).GetProperties();
            foreach (PropertyInfo p in props)
            {
                if (p.PropertyType.IsEquivalentTo(typeof(bool)))
                {
                    ConfigSection[] attr = (ConfigSection[])p.GetCustomAttributes(typeof(ConfigSection), false);
                    if (attr.Length > 0 && attr[0].YesNoBool)
                        file += ((bool)p.GetValue(this) ? "/" : "/no") + p.Name.ToLower();

                    else
                    {
                        file += "/" + p.Name.ToLower() + " ";
                        file += (((bool)p.GetValue(this)) ? "1" : "0");
                    }
                }
                else file += "/" + p.Name.ToLower() + " ";

                if (p.PropertyType.IsEquivalentTo(typeof(ushort)))
                    file += ((ushort)p.GetValue(this)).ToString();

                else if (p.PropertyType.IsEquivalentTo(typeof(int)))
                    file += ((int)p.GetValue(this)).ToString();

                else if (p.PropertyType.IsEquivalentTo(typeof(string)))
                    file += "\"" + (string)p.GetValue(this) + "\"";

                file += "\r\n";
            }

            try
            {
                core.Files.WriteFileText(fileName, file);
                Logger.Log(LogLevel.Verbose, "Server settings saved.");
            }
            catch (Exception e)
            {
                Logger.Log(LogLevel.Error, "Failed to write to file {0} ({1})", fileName, e.ToString());
            }
        }

19 Source : MockThreadManagerServices.cs
with GNU General Public License v3.0
from k3ldar

public bool ContainsRegisteredStartupThread(string threadName, Type type)
        {
            return _registeredThreads.ContainsKey(threadName) &&
                _registeredThreads[threadName].IsEquivalentTo(type);
        }

19 Source : BuildScripts.cs
with GNU General Public License v3.0
from Kermalis

private void ParseAndWriteValue(string str, Type targetType, Dictionary<string, string> defines)
    {
        bool varAble = IsTypeVarAble(targetType);
    top:
        foreach (KeyValuePair<string, string> tup in defines)
        {
            if (str != tup.Key)
            {
                continue;
            }
            str = tup.Value;
            goto top;
        }
        foreach (KeyValuePair<Type, string> tup in ScriptBuilderHelper.EnumDefines)
        {
            string prefix = tup.Value;
            if (!str.StartsWith(prefix))
            {
                continue;
            }
            str = str.Substring(prefix.Length);

            Type type = tup.Key;
            if (varAble && type.IsEquivalentTo(typeof(Var)))
            {
                uint wVal = ushort.MaxValue + 1 + Convert.ToUInt32(Enum.Parse<Var>(str));
                _writer.Write(wVal);
                return;
            }

            WriteValue(Enum.Parse(type, str), targetType);
            return;
        }
        // Did not find an enum value, so write just a parsed int value
        WriteValue(ParseInt(str), targetType);
    }

19 Source : BuildScripts.cs
with GNU General Public License v3.0
from Kermalis

private void WriteValue(object value, Type targetType)
    {
        // Var should be written as its underlying type only
        if (targetType.IsEquivalentTo(typeof(Var)))
        {
            _writer.Write((Var)Enum.ToObject(typeof(Var), value));
            return;
        }

        if (targetType.IsEnum)
        {
            targetType = targetType.GetEnumUnderlyingType();
        }
        switch (targetType.FullName)
        {
            case "System.Byte":
            case "System.SByte":
            case "System.Int16":
            case "System.UInt16":
            case "System.Int32":
            case "System.UInt32": _writer.Write(Convert.ToInt32(value)); break;
            case "System.Int64":
            case "System.UInt64": _writer.Write(Convert.ToInt64(value)); break;
            default: throw new Exception();
        }
    }

19 Source : BuildScripts.cs
with GNU General Public License v3.0
from Kermalis

private static bool IsTypeVarAble(Type type)
    {
        if (type.IsEquivalentTo(typeof(Var)))
        {
            return false;
        }

        if (type.IsEnum)
        {
            type = Enum.GetUnderlyingType(type);
        }
        switch (type.FullName)
        {
            case "System.Byte":
            case "System.SByte":
            case "System.Int16":
            case "System.UInt16": return true;
        }
        return false;
    }

19 Source : QueryableTests.cs
with Apache License 2.0
from kevin-montrose

static bool Equivalent(Type a, Type b)
        {
            if (a == b) return true;
            if (a.IsEquivalentTo(b) && b.IsEquivalentTo(a)) return true;
            if (a.IsreplacedignableFrom(b) && b.IsreplacedignableFrom(a)) return true;

            // eh, not strictly true 
            if (a.IsGenericParameter && b.IsGenericParameter) return true;

            if (!a.IsGenericType && !b.IsGenericType) return false;
            if (a.IsGenericType && !b.IsGenericType) return false;
            if (!a.IsGenericType && b.IsGenericType) return false;
            
            var aParams = a.GetGenericArguments();
            var bParams = b.GetGenericArguments();

            if (aParams?.Length != bParams?.Length) return false;
            
            for(var i = 0; i < aParams.Length; i++)
            {
                var aP = aParams[i];
                var bP = bParams[i];

                if (!Equivalent(aP, bP)) return false;
            }

            return true;
        }

19 Source : TypeUtil.cs
with MIT License
from klanggames

internal static bool AreEquivalent(Type t1, Type t2) {
            if (!(t1 == t2))
                return t1.IsEquivalentTo(t2);
            return true;
        }

19 Source : JwtExtensions.cs
with MIT License
from LtiLibrary

private static T GetClaimValues<T>(this JwtPayload payload, string type)
        {
            var values = payload.Claims
                .Where(c => c.Type == type)
                .Select(c => c.Value).ToArray();

            if (0 == values.Length)
                return default(T);

            var elementType = typeof(T).GetElementType();
            if (elementType != null && elementType.IsClreplaced && !elementType.IsEquivalentTo(typeof(string)))
            {
                return JsonConvert.DeserializeObject<T>("[" + string.Join(",", values) + "]");
            }
            return JsonConvert.DeserializeObject<T>("[\"" + string.Join("\",\"", values) + "\"]");
        }

19 Source : InterpreterArchitecture.cs
with Apache License 2.0
from microsoft

public int CompareTo(InterpreterArchitecture other) {
            // We implement the full comparison here rather than delegating to
            // subclreplacedes so that we have some way to handle extra
            // architectures being injected while ensuring that the
            // standard ones take priority.

            // The ordering is:
            //      x86
            //      x64
            //      anything else sorted by type name
            //      Unknown

            if (GetType().IsEquivalentTo(other.GetType())) {
                return 0;
            }

            if (this is X86Architecture) {
                return -1;
            }
            if (this is X64Architecture) {
                if (other is X86Architecture) {
                    return 1;
                }
                return -1;
            }
            if (this is UnknownArchitecture) {
                return 1;
            }
            if (other is UnknownArchitecture) {
                return -1;
            }

            return string.CompareOrdinal(GetType().Name, other.GetType().Name);
        }

19 Source : InterpreterArchitecture.cs
with Apache License 2.0
from microsoft

public bool Equals(InterpreterArchitecture other) => other != null && GetType().IsEquivalentTo(other.GetType());

19 Source : AttributedPartDiscoveryV1.cs
with MIT License
from microsoft

public override bool IsExportFactoryType(Type type)
        {
            if (type != null && type.GetTypeInfo().IsGenericType)
            {
                var typeDefinition = type.GetGenericTypeDefinition();
                if (typeDefinition.Equals(typeof(ExportFactory<>)) || typeDefinition.IsEquivalentTo(typeof(ExportFactory<,>)))
                {
                    return true;
                }
            }

            return false;
        }

19 Source : MemberRef.cs
with MIT License
from microsoft

public virtual bool Equals(MemberRef? other)
        {
            if (other == null || !this.GetType().IsEquivalentTo(other.GetType()))
            {
                return false;
            }

            if (this.cachedMemberInfo != null && other.cachedMemberInfo != null)
            {
                if (this.cachedMemberInfo == other.cachedMemberInfo)
                {
                    return true;
                }
            }

            if (this.metadataToken.HasValue && other.metadataToken.HasValue && this.DeclaringType.replacedemblyId.Equals(other.DeclaringType.replacedemblyId))
            {
                if (this.metadataToken.Value != other.metadataToken.Value)
                {
                    return false;
                }
            }
            else
            {
                if (!this.EqualsByTypeLocalMetadata(other))
                {
                    return false;
                }
            }

            return EqualityComparer<TypeRef>.Default.Equals(this.DeclaringType, other.DeclaringType);
        }

19 Source : ReflectionHelpers.cs
with MIT License
from microsoft

internal static string GetTypeName(Type type, bool genericTypeDefinition, bool evenNonPublic, HashSet<replacedembly>? relevantreplacedemblies, HashSet<Type>? relevantEmbeddedTypes)
        {
            Requires.NotNull(type, nameof(type));

            if (type.IsArray)
            {
                return GetTypeName(type.GetElementType()!, genericTypeDefinition, evenNonPublic, relevantreplacedemblies, relevantEmbeddedTypes) + "[]";
            }

            if (relevantreplacedemblies != null)
            {
                relevantreplacedemblies.Add(type.GetTypeInfo().replacedembly);
                relevantreplacedemblies.UnionWith(GetAllBaseTypesAndInterfaces(type).Select(t => t.GetTypeInfo().replacedembly));
            }

            if (relevantEmbeddedTypes != null)
            {
                AddEmbeddedInterfaces(type, relevantEmbeddedTypes);
            }

            if (type.IsGenericParameter)
            {
                return type.Name;
            }

            if (!IsPublic(type, checkGenericTypeArgs: true) && !evenNonPublic)
            {
                return GetTypeName(type.GetTypeInfo().BaseType ?? typeof(object), genericTypeDefinition, evenNonPublic, relevantreplacedemblies, relevantEmbeddedTypes);
            }

            if (type.IsEquivalentTo(typeof(ValueType)))
            {
                return "object";
            }

            string result = string.Empty;
            if (type.DeclaringType != null)
            {
                // Take care to propagate generic type arguments to the declaring type.
                var declaringTypeInfo = type.DeclaringType.GetTypeInfo();
                var declaringType = declaringTypeInfo.ContainsGenericParameters && type.GenericTypeArguments.Length > declaringTypeInfo.GenericTypeArguments.Length
                    ? type.DeclaringType.MakeGenericType(type.GenericTypeArguments.Take(declaringTypeInfo.GenericTypeParameters.Length).ToArray())
                    : type.DeclaringType;
                result = GetTypeName(declaringType, genericTypeDefinition, evenNonPublic, relevantreplacedemblies, relevantEmbeddedTypes) + ".";
            }

            if (genericTypeDefinition)
            {
                result += FilterTypeNameForGenericTypeDefinition(type, type.DeclaringType == null);
            }
            else
            {
                string[] typeArguments = type.GetTypeInfo().GenericTypeArguments.Select(t => GetTypeName(t, false, evenNonPublic, relevantreplacedemblies, relevantEmbeddedTypes)).ToArray();
                result += ReplaceBackTickWithTypeArgs(type.DeclaringType == null ? (type.FullName ?? type.Name) : type.Name, typeArguments);
            }

            return result;
        }

19 Source : AttributedPartDiscoveryTestBase.cs
with MIT License
from microsoft

[Fact]
        public async Task replacedemblyDiscoveryOmitsNonDiscoverableParts_Combined()
        {
            var combined = PartDiscovery.Combine(this.DiscoveryService, new PartDiscoveryAllTypesMock());
            var result = await combined.CreatePartsAsync(typeof(NonDiscoverablePart).GetTypeInfo().replacedembly);

            replacedert.DoesNotContain(result.Parts, p => p.Type.GetTypeInfo().IsEquivalentTo(typeof(NonPart)));
            replacedert.DoesNotContain(result.Parts, p => p.Type.GetTypeInfo().IsEquivalentTo(typeof(NonDiscoverablePart)));
            replacedert.DoesNotContain(result.Parts, p => p.Type.GetTypeInfo().IsEquivalentTo(typeof(NonDiscoverablePartV1)));
            replacedert.DoesNotContain(result.Parts, p => p.Type.GetTypeInfo().IsEquivalentTo(typeof(NonDiscoverablePartV2)));

            replacedert.Contains(result.Parts, p => p.Type.GetTypeInfo().IsEquivalentTo(typeof(DiscoverablePart1)));
            replacedert.Contains(result.Parts, p => p.Type.GetTypeInfo().IsEquivalentTo(typeof(DiscoverablePart2)));
        }

19 Source : ComposedPart.cs
with MIT License
from microsoft

private static bool IsAllowedImportManyParameterType(Type importSiteType)
        {
            Requires.NotNull(importSiteType, nameof(importSiteType));
            if (importSiteType.IsArray)
            {
                return true;
            }

            if (importSiteType.GetTypeInfo().IsGenericType && importSiteType.GetTypeInfo().GetGenericTypeDefinition().IsEquivalentTo(typeof(IEnumerable<>)))
            {
                return true;
            }

            return false;
        }

19 Source : LazyMetadataWrapper.cs
with MIT License
from microsoft

internal static bool TryGetLoadSafeValueTypeRef(IReadOnlyDictionary<string, object?> metadata, string key, Resolver resolver, out object? value)
        {
            Requires.NotNull(metadata, nameof(metadata));

            if (metadata is LazyMetadataWrapper lazyMetadata && lazyMetadata.direction == Direction.ToOriginalValue)
            {
                metadata = lazyMetadata.underlyingMetadata;
            }

            if (!metadata.TryGetValue(key, out object? innerValue))
            {
                value = null;
                return false;
            }

            if (innerValue is ISubsreplacedutedValue subsreplacedutedValue)
            {
                value = subsreplacedutedValue.SubsreplacedutedValueTypeRef;
            }
            else if (innerValue != null && typeof(object[]).IsEquivalentTo(innerValue.GetType()))
            {
                value = ((object[])innerValue).Select(v => TypeRef.Get(v?.GetType(), resolver)).ToArray();
            }
            else
            {
                value = TypeRef.Get(innerValue?.GetType(), resolver);
            }

            return true;
        }

19 Source : AttributedPartDiscoveryTestBase.cs
with MIT License
from microsoft

[Fact]
        public async Task replacedemblyDiscoveryFindsTopLevelParts()
        {
            var result = await this.DiscoveryService.CreatePartsAsync(typeof(NonDiscoverablePart).GetTypeInfo().replacedembly);
            replacedert.Contains(result.Parts, p => p.Type.GetTypeInfo().IsEquivalentTo(typeof(DiscoverablePart1)));
            replacedert.Contains(result.Parts, p => p.Type.GetTypeInfo().IsEquivalentTo(typeof(DiscoverablePart2)));
        }

19 Source : AttributedPartDiscoveryTestBase.cs
with MIT License
from microsoft

[Fact]
        public async Task replacedemblyDiscoveryOmitsNonDiscoverableParts()
        {
            var result = await this.DiscoveryService.CreatePartsAsync(typeof(NonDiscoverablePart).GetTypeInfo().replacedembly);
            replacedert.DoesNotContain(result.Parts, p => p.Type.GetTypeInfo().IsEquivalentTo(typeof(NonPart)));
            replacedert.DoesNotContain(result.Parts, p => p.Type.GetTypeInfo().IsEquivalentTo(typeof(NonDiscoverablePart)));
        }

19 Source : PartDiscovery.cs
with MIT License
from microsoft

protected internal static ImmutableHashSet<IImportSatisfiabilityConstraint> GetExportTypeIdenreplacedyConstraints(Type contractType)
        {
            Requires.NotNull(contractType, nameof(contractType));

            var constraints = ImmutableHashSet<IImportSatisfiabilityConstraint>.Empty;

            if (!contractType.IsEquivalentTo(typeof(object)))
            {
                constraints = constraints.Add(new ExportTypeIdenreplacedyConstraint(contractType));
            }

            return constraints;
        }

19 Source : AttributedPartDiscoveryTestBase.cs
with MIT License
from microsoft

[Fact]
        public async Task replacedemblyDiscoveryFindsNestedParts()
        {
            var result = await this.DiscoveryService.CreatePartsAsync(typeof(NonDiscoverablePart).GetTypeInfo().replacedembly);
            replacedert.Contains(result.Parts, p => p.Type.GetTypeInfo().IsEquivalentTo(typeof(OuterClreplaced.NestedPart)));
        }

19 Source : DelegatingType.cs
with MIT License
from microsoftarchive

public override bool IsEquivalentTo(Type other)
        {
            return _type.IsEquivalentTo(other);
        }

19 Source : PluginManager.cs
with MIT License
from OfficeDev

public ObservableCollection<PluginDetails> InitializePlugins(ApplicationData applicationData)
        {
            List<ITunnelRelayPlugin> pluginInstances = new List<ITunnelRelayPlugin>();
            ObservableCollection<PluginDetails> plugins = new ObservableCollection<PluginDetails>();
            pluginInstances.Add(new HeaderAdditionPlugin());
            pluginInstances.Add(new HeaderRemovalPlugin());
            string pluginDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Plugins");

            if (Directory.Exists(pluginDirectory))
            {
                Directory.EnumerateFiles(pluginDirectory, "*.dll").ToList().ForEach(dll =>
                {
                    try
                    {
                        replacedembly replacedembly = replacedembly.LoadFrom(dll);
                        foreach (Type pluginType in replacedembly.GetExportedTypes().Where(type => type.GetInterfaces().Contains(typeof(ITunnelRelayPlugin))))
                        {
                            this.logger.LogInformation("Loading plugin '{0}'", pluginType.FullName);
                            pluginInstances.Add(Activator.CreateInstance(pluginType) as ITunnelRelayPlugin);
                        }
                    }
                    catch (Exception ex)
                    {
                        this.logger.LogError(ex, "Plugin discovery hit an error!");
                    }
                });
            }

            pluginInstances.ForEach(plugin =>
            {
                PluginDetails pluginDetails = new PluginDetails(applicationData)
                {
                    PluginInstance = plugin,
                    PluginSettings = new ObservableCollection<PluginSettingDetails>(),
                    IsEnabled = applicationData.EnabledPlugins.Contains(plugin.GetType().FullName),
                };

                try
                {
                    IEnumerable<PropertyInfo> settingProperties = plugin.GetType().GetProperties().Where(memberInfo => memberInfo.GetCustomAttribute(typeof(PluginSettingAttribute)) != null);

                    foreach (PropertyInfo setting in settingProperties)
                    {
                        if (!setting.PropertyType.IsEquivalentTo(typeof(string)))
                        {
                            throw new InvalidDataException("Plugin settings can only be of string datatype");
                        }

                        PluginSettingDetails pluginSetting = new PluginSettingDetails(applicationData)
                        {
                            AttributeData = setting.GetCustomAttribute<PluginSettingAttribute>(),
                            PluginInstance = plugin,
                            PropertyDetails = setting,
                        };

                        if (applicationData.PluginSettingsMap.TryGetValue(pluginDetails.PluginInstance.GetType().FullName, out Dictionary<string, string> pluginSettingsVal))
                        {
                            if (pluginSettingsVal.TryGetValue(pluginSetting.PropertyDetails.Name, out string propertyValue))
                            {
                                pluginSetting.Value = propertyValue;
                            }
                        }

                        pluginDetails.PluginSettings.Add(pluginSetting);
                    }

                    if (pluginDetails.IsEnabled)
                    {
                        this.logger.LogInformation("Initializing '{0}'.", pluginDetails.PluginInstance.PluginName);
                        pluginDetails.InitializePlugin();
                    }
                }
                catch (Exception ex)
                {
                    this.logger.LogError(ex, "Plugin init failed");
                }

                plugins.Add(pluginDetails);
            });

            return plugins;
        }

19 Source : IsNotTypeToVisibilityConverter.cs
with MIT License
from RayCarrot

public override Visibility ConvertValue(object value, Type targetType, Type parameter, CultureInfo culture) => 
            value.GetType().IsEquivalentTo(parameter) ? Visibility.Collapsed : Visibility.Visible;

19 Source : IsTypeToVisibilityConverter.cs
with MIT License
from RayCarrot

public override Visibility ConvertValue(object value, Type targetType, Type parameter, CultureInfo culture) => 
            value.GetType().IsEquivalentTo(parameter) ? Visibility.Visible : Visibility.Collapsed;

19 Source : TypeUtils.cs
with MIT License
from reaqtive

public static bool AreEquivalent(Type t1, Type t2)
        {
            return t1 == t2 || t1.IsEquivalentTo(t2);
        }

19 Source : TypeUtils.cs
with MIT License
from reaqtive

public static bool AreEquivalent(Type first, Type second)
        {
            return first == second
                || first.GetTypeInfo().IsEquivalentTo(second.GetTypeInfo())
                ;
        }

19 Source : CLRType.cs
with MIT License
from scottyboy805

public override bool IsEquivalentTo(Type other)
        {
            return base.IsEquivalentTo(other);
        }

19 Source : Enum.cs
with MIT License
from spaceflint7

public bool HasFlag(Enum flag)
        {
            ThrowHelper.ThrowIfNull(flag);
            if (! this.GetType().IsEquivalentTo(flag.GetType()))
                throw new System.ArgumentException();
            var v = flag.GetLong();
            return (GetLong() & v) == v;
        }

19 Source : CreateSchemaObject.cs
with Apache License 2.0
from specklesystems

protected override void SolveInstance(IGH_DataAccess DA)
    {
      if (readFailed)
      {
        AddRuntimeMessage(GH_RuntimeMessageLevel.Error,
          "This component has changed or cannot be found, please create a new one");
        return;
      }

      if (SelectedConstructor is null)
      {
        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No schema has been selected.");
        return;
      }

      var units = Units.GetUnitsFromString(Rhino.RhinoDoc.ActiveDoc.GetUnitSystemName(true, false, false, false));

      List<object> cParamsValues = new List<object>();
      var cParams = SelectedConstructor.GetParameters();
      object mainSchemaObj = null;
      for (var i = 0; i < cParams.Length; i++)
      {
        var cParam = cParams[i];
        var param = Params.Input[i];
        object objectProp = null;
        if (param.Access == GH_ParamAccess.list)
        {
          var inputValues = new List<object>();
          DA.GetDataList(i, inputValues);
          if (!inputValues.Any() && !param.Optional)
          {
            AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Input list `" + param.Name + "` is empty.");
            return;
          }

          try
          {
            inputValues = inputValues.Select(x => ExtractRealInputValue(x)).ToList();
            objectProp = GetObjectListProp(param, inputValues, cParam.ParameterType);
          }
          catch (Exception e)
          {
            AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.InnerException?.Message ?? e.Message);
            return;
          }
        }
        else if (param.Access == GH_ParamAccess.item)
        {
          object inputValue = null;
          DA.GetData(i, ref inputValue);
          var extractRealInputValue = ExtractRealInputValue(inputValue);
          objectProp = GetObjectProp(param, extractRealInputValue, cParam.ParameterType);
        }

        cParamsValues.Add(objectProp);
        if (CustomAttributeData.GetCustomAttributes(cParam)
          ?.Where(o => o.AttributeType.IsEquivalentTo(typeof(SchemaMainParam)))?.Count() > 0)
          mainSchemaObj = objectProp;
      }


      object schemaObject = null;
      try
      {
        schemaObject = SelectedConstructor.Invoke(cParamsValues.ToArray());
        ((Base)schemaObject).applicationId = $"{Seed}-{SelectedConstructor.DeclaringType.FullName}-{DA.Iteration}";
        ((Base)schemaObject)["units"] = units;
      }
      catch (Exception e)
      {
        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.InnerException?.Message ?? e.Message);
        return;
      }

      // create commit obj from main geometry param and try to attach schema obj. use schema obj if no main geom param was found.
      Base commitObj = (Base)schemaObject;
      if (UseSchemaTag)
      {
        commitObj = commitObj.ShallowCopy();
        try
        {
          if (mainSchemaObj == null)
          {
            UseSchemaTag = false;
            throw new Exception("Schema tag is not supported for this object type, will return Schema object instead.");
          }

          commitObj = ((Base)mainSchemaObj).ShallowCopy();
          commitObj["@SpeckleSchema"] = schemaObject;
          commitObj["units"] = units;
        }
        catch (Exception e)
        {
          AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, e.Message);
        }
      }

      // Finally, add any custom props created by the user.
      for (var j = cParams.Length; j < Params.Input.Count; j++)
      {
        // Additional props added to the object
        var ghParam = Params.Input[j];
        if (ghParam.Access == GH_ParamAccess.item)
        {
          object input = null;
          DA.GetData(j, ref input);

          commitObj[ghParam.Name] = Utilities.TryConverreplacedemToSpeckle(input, Converter);
        }
        else if (ghParam.Access == GH_ParamAccess.list)
        {
          List<object> input = new List<object>();
          DA.GetDataList(j, input);
          commitObj[ghParam.Name] = input.Select(i => Utilities.TryConverreplacedemToSpeckle(i, Converter)).ToList();
        }
      }

      DA.SetData(0, new GH_SpeckleBase() { Value = commitObj });
    }

19 Source : CreateSchemaObjectBase.cs
with Apache License 2.0
from specklesystems

public override void AppendAdditionalMenuItems(ToolStripDropDown menu)
    {
      base.AppendAdditionalMenuItems(menu);
      Menu_AppendSeparator(menu);
      var schemaConversionHeader = Menu_AppendItem(menu, "Select a Schema conversion option:");

      ParameterInfo mainParam = null;

      try
      {
        mainParam = SelectedConstructor.GetParameters().FirstOrDefault(cParam => CustomAttributeData.GetCustomAttributes(cParam)
          ?.Where(o => o.AttributeType.IsEquivalentTo(typeof(SchemaMainParam)))?.Count() > 0);
      }
      catch (Exception e)
      {
      }
      
      var objecreplacedem = schemaConversionHeader.DropDownItems.Add("Convert as Schema object.") as ToolStripMenuItem;
      objecreplacedem.Checked = !UseSchemaTag;
      objecreplacedem.ToolTipText = "The default behaviour. Output will be the specified object schema.";
      
      var tagItem = schemaConversionHeader.DropDownItems.Add($"Convert as {mainParam?.Name ?? "geometry"} with {Name} attached") as ToolStripMenuItem;
      tagItem.Checked = UseSchemaTag;
      tagItem.Enabled = mainParam != null;
      tagItem.ToolTipText =
        "Enables Schema conversion while prioritizing the geometry over the schema.\n\nSchema information will e stored in a '@SpeckleSchema' property.";

      var speckleBaseParam = (Params.Output[0] as SpeckleBaseParam);
      tagItem.Click += (sender, args) =>
      {
        UseSchemaTag = true;
        speckleBaseParam.UseSchemaTag = UseSchemaTag;
        speckleBaseParam.ExpirePreview(true);
        UserSetSchemaTag = true;
        ExpireSolution(true);
      };

      objecreplacedem.Click += (sender, args) =>
      {
        UseSchemaTag = false;
        speckleBaseParam.UseSchemaTag = UseSchemaTag;
        speckleBaseParam.ExpirePreview(true);

        UserSetSchemaTag = true;
        ExpireSolution(true);
      };

    }

19 Source : CreateSchemaObject.cs
with Apache License 2.0
from specklesystems

public override void AppendAdditionalMenuItems(ToolStripDropDown menu)
    {
      base.AppendAdditionalMenuItems(menu);
      Menu_AppendSeparator(menu);
      var schemaConversionHeader = Menu_AppendItem(menu, "Select a Schema conversion option:");
      ParameterInfo mainParam = null;
      try
      {
        mainParam = SelectedConstructor
          .GetParameters()
          .First(cParam => CustomAttributeData
            .GetCustomAttributes(cParam)
            .Any(o => o.AttributeType.IsEquivalentTo(typeof(SchemaMainParam))));
      }
      catch (Exception e)
      {
      }

      var objecreplacedem = schemaConversionHeader.DropDownItems.Add("Convert as Schema object.") as ToolStripMenuItem;
      objecreplacedem.Checked = !UseSchemaTag;
      objecreplacedem.ToolTipText = "The default behaviour. Output will be the specified object schema.";

      var tagItem =
        schemaConversionHeader.DropDownItems.Add($"Convert as {mainParam.Name ?? "geometry"} with {Name} attached") as
          ToolStripMenuItem;
      tagItem.Checked = UseSchemaTag;
      tagItem.Enabled = mainParam != null;
      tagItem.ToolTipText =
        "Enables Schema conversion while prioritizing the geometry over the schema.\n\nSchema information will e stored in a '@SpeckleSchema' property.";

      var speckleBaseParam = (Params.Output[0] as SpeckleBaseParam);
      tagItem.Click += (sender, args) =>
      {
        UseSchemaTag = true;
        UserSetSchemaTag = true;
        speckleBaseParam.UseSchemaTag = UseSchemaTag;
        speckleBaseParam.ExpirePreview(true);
        ExpireSolution(true);
      };

      objecreplacedem.Click += (sender, args) =>
      {
        UseSchemaTag = false;
        UserSetSchemaTag = true;
        speckleBaseParam.UseSchemaTag = UseSchemaTag;
        speckleBaseParam.ExpirePreview(true);
        ExpireSolution(true);
      };
    }

19 Source : CreateSchemaObjectBase.cs
with Apache License 2.0
from specklesystems

protected override void SolveInstance(IGH_DataAccess DA)
    {
      if (readFailed)
      {
        AddRuntimeMessage(GH_RuntimeMessageLevel.Error,
          "This component has changed or cannot be found, please create a new one");
        return;
      }

      if (SelectedConstructor is null)
      {
        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No schema has been selected.");
        return;
      }

      var units = Units.GetUnitsFromString(Rhino.RhinoDoc.ActiveDoc.GetUnitSystemName(true, false, false, false));

      List<object> cParamsValues = new List<object>();
      var cParams = SelectedConstructor.GetParameters();
      object mainSchemaObj = null;
      for (var i = 0; i < cParams.Length; i++)
      {
        var cParam = cParams[i];
        var param = Params.Input[i];
        object objectProp = null;
        if (param.Access == GH_ParamAccess.list)
        {
          var inputValues = new List<object>();
          DA.GetDataList(i, inputValues);
          if (!inputValues.Any() && !param.Optional)
          {
            AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Input list `" + param.Name + "` is empty.");
            return;
          }

          try
          {
            inputValues = inputValues.Select(x => ExtractRealInputValue(x)).ToList();
            objectProp = GetObjectListProp(param, inputValues, cParam.ParameterType);
          }
          catch (Exception e)
          {
            AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.InnerException?.Message ?? e.Message);
            return;
          }
        }
        else if (param.Access == GH_ParamAccess.item)
        {
          object inputValue = null;
          DA.GetData(i, ref inputValue);
          var extractRealInputValue = ExtractRealInputValue(inputValue);
          objectProp = GetObjectProp(param, extractRealInputValue, cParam.ParameterType);
        }

        cParamsValues.Add(objectProp);
        if (CustomAttributeData.GetCustomAttributes(cParam)
          ?.Where(o => o.AttributeType.IsEquivalentTo(typeof(SchemaMainParam)))?.Count() > 0)
          mainSchemaObj = objectProp;
      }


      object schemaObject = null;
      try
      {
        schemaObject = SelectedConstructor.Invoke(cParamsValues.ToArray());
        ((Base)schemaObject).applicationId = $"{Seed}-{SelectedConstructor.DeclaringType.FullName}-{DA.Iteration}";
        ((Base)schemaObject)["units"] = units;
      }
      catch (Exception e)
      {
        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.InnerException?.Message ?? e.Message);
        return;
      }

      // create commit obj from main geometry param and try to attach schema obj. use schema obj if no main geom param was found.
      Base commitObj = (Base)schemaObject;
      if (UseSchemaTag)
      {
        commitObj = commitObj.ShallowCopy();
        try
        {
          if (mainSchemaObj == null)
          {
            UseSchemaTag = false;
            ((SpeckleBaseParam)Params.Output[0]).UseSchemaTag = UseSchemaTag;
            throw new Exception("Schema tag is not supported for this object type, will return Schema object instead.");
          }

          commitObj = ((Base)mainSchemaObj).ShallowCopy();
          commitObj["@SpeckleSchema"] = schemaObject;
          commitObj["units"] = units;
        }
        catch (Exception e)
        {
          AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, e.Message);
        }
      }

      // Finally, add any custom props created by the user.
      for (var j = cParams.Length; j < Params.Input.Count; j++)
      {
        // Additional props added to the object
        var ghParam = Params.Input[j];
        if (ghParam.Access == GH_ParamAccess.item)
        {
          object input = null;
          DA.GetData(j, ref input);

          commitObj[ghParam.Name] = Utilities.TryConverreplacedemToSpeckle(input, Converter);
        }
        else if (ghParam.Access == GH_ParamAccess.list)
        {
          List<object> input = new List<object>();
          DA.GetDataList(j, input);
          commitObj[ghParam.Name] = input.Select(i => Utilities.TryConverreplacedemToSpeckle(i, Converter)).ToList();
        }
      }

      DA.SetData(0, new GH_SpeckleBase() { Value = commitObj });
    }

19 Source : RuntimeType.cs
with MIT License
from Team-RTCLI

public override bool IsEnumDefined(object value)
        {
            if (value == null)
                throw new ArgumentNullException(nameof(value));

            if (!IsEnum)
                throw new ArgumentException(SR.Arg_MustBeEnum, "enumType");

            // Check if both of them are of the same type
            RuntimeType valueType = (RuntimeType)value.GetType();

            // If the value is an Enum then we need to extract the underlying value from it
            if (valueType.IsEnum)
            {
                if (!valueType.IsEquivalentTo(this))
                    throw new ArgumentException(SR.Format(SR.Arg_EnumAndObjectMustBeSameType, valueType, this));

                valueType = (RuntimeType)valueType.GetEnumUnderlyingType();
            }

            // If a string is preplaceded in
            if (valueType == StringType)
            {
                // Get all of the Fields, calling GetHashEntry directly to avoid copying
                string[] names = Enum.InternalGetNames(this);
                return Array.IndexOf(names, value) >= 0;
            }

            // If an enum or integer value is preplaceded in
            if (IsIntegerType(valueType))
            {
                RuntimeType underlyingType = Enum.InternalGetUnderlyingType(this);
                if (underlyingType != valueType)
                    throw new ArgumentException(SR.Format(SR.Arg_EnumUnderlyingTypeAndObjectMustBeSameType, valueType, underlyingType));

                ulong[] ulValues = Enum.InternalGetValues(this);
                ulong ulValue = Enum.ToUInt64(value);

                return Array.BinarySearch(ulValues, ulValue) >= 0;
            }
            else
            {
                throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType);
            }
        }

See More Examples