Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 61 additions & 3 deletions AutoMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,70 @@ namespace AutoMapper
{
public class AutoMapper
{
public void Map(object source, object target)
public static TTarget Map<TSource, TTarget>(TSource source)
where TTarget : new()
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (target == null) throw new ArgumentNullException(nameof(target));
if (source == null) return default!;

TTarget target = new TTarget();

var sourceProps = typeof(TSource).GetProperties();
var targetProps = typeof(TTarget).GetProperties();

foreach (var tProp in targetProps)
{
if (!tProp.CanWrite) continue;

// Case-insensitive match
var sProp = sourceProps.FirstOrDefault(
sp => string.Equals(sp.Name, tProp.Name, StringComparison.OrdinalIgnoreCase)
);

if (sProp == null) continue;

var sValue = sProp.GetValue(source);

if (sValue == null)
{
// If nullable → non-nullable, assign default value ("" for string)
if (!IsNullable(tProp.PropertyType))
{
tProp.SetValue(target, GetDefaultValue(tProp.PropertyType));
}
continue;
}

// Type matches → direct assign
if (tProp.PropertyType == sProp.PropertyType)
{
tProp.SetValue(target, sValue);
continue;
}

// Try convert types (string ↔ int, etc.)
try
{
var converted = Convert.ChangeType(sValue, tProp.PropertyType);
tProp.SetValue(target, converted);
}
catch
{
// ignore conversion errors
}
}

return target;
}

private static bool IsNullable(Type t)
{
return !t.IsValueType || Nullable.GetUnderlyingType(t) != null;
}

private static object GetDefaultValue(Type t)
{
if (t == typeof(string)) return string.Empty;
return Activator.CreateInstance(t)!;
}
}
}