Replace terniary null checks with coalescing.

This commit is contained in:
Paul Chote
2021-03-07 21:22:00 +00:00
committed by teinarss
parent 2473b8763b
commit d52ba83f96
43 changed files with 72 additions and 73 deletions

View File

@@ -282,13 +282,13 @@ namespace OpenRA.Mods.Common.Orders
footprint.Add(t, MakeCellType(isCloseEnough && world.IsCellBuildable(t, actorInfo, buildingInfo) && (resourceLayer == null || resourceLayer.GetResourceType(t) == null)));
}
return preview != null ? preview.Render(wr, topLeft, footprint) : Enumerable.Empty<IRenderable>();
return preview?.Render(wr, topLeft, footprint) ?? Enumerable.Empty<IRenderable>();
}
IEnumerable<IRenderable> IOrderGenerator.RenderAnnotations(WorldRenderer wr, World world)
{
var preview = variants[variant].Preview;
return preview != null ? preview.RenderAnnotations(wr, TopLeft) : Enumerable.Empty<IRenderable>();
return preview?.RenderAnnotations(wr, TopLeft) ?? Enumerable.Empty<IRenderable>();
}
string IOrderGenerator.GetCursor(World world, CPos cell, int2 worldPixel, MouseInput mi)

View File

@@ -48,7 +48,7 @@ namespace OpenRA.Mods.Common.Scripting
[Desc("Return or set the time limit (in ticks). When setting, the time limit will count from now. Setting the time limit to 0 will disable it.")]
public int TimeLimit
{
get => tlm != null ? tlm.TimeLimit : 0;
get => tlm?.TimeLimit ?? 0;
set
{
@@ -62,7 +62,7 @@ namespace OpenRA.Mods.Common.Scripting
[Desc("The notification string used for custom time limit warnings. See the TimeLimitManager trait documentation for details.")]
public string TimeLimitNotification
{
get => tlm != null ? tlm.Notification : null;
get => tlm?.Notification;
set
{

View File

@@ -393,7 +393,7 @@ namespace OpenRA.Mods.Common.Traits
protected virtual WRot CalculateMuzzleOrientation(Actor self, Barrel b)
{
return WRot.FromYaw(b.Yaw).Rotate(turret != null ? turret.WorldOrientation : self.Orientation);
return WRot.FromYaw(b.Yaw).Rotate(turret?.WorldOrientation ?? self.Orientation);
}
public Actor Actor => self;

View File

@@ -119,7 +119,7 @@ namespace OpenRA.Mods.Common.Traits
actor =>
{
var init = actor.GetInitOrDefault<StanceInit>(this);
var stance = init != null ? init.Value : InitialStance;
var stance = init?.Value ?? InitialStance;
return stances[(int)stance];
},
(actor, value) => actor.ReplaceInit(new StanceInit(this, (UnitStance)stances.IndexOf(value))));

View File

@@ -141,7 +141,7 @@ namespace OpenRA.Mods.Common.Traits
Info.ConstructionYardTypes.Contains(a.Info.Name))
.RandomOrDefault(world.LocalRandom);
return randomConstructionYard != null ? randomConstructionYard.Location : initialBaseCenter;
return randomConstructionYard?.Location ?? initialBaseCenter;
}
public CPos DefenseCenter => defenseCenter;

View File

@@ -55,7 +55,7 @@ namespace OpenRA.Mods.Common.Traits
Info.ConstructionYardTypes.Contains(a.Info.Name))
.RandomOrDefault(world.LocalRandom);
return randomConstructionYard != null ? randomConstructionYard.Location : initialBaseCenter;
return randomConstructionYard?.Location ?? initialBaseCenter;
}
readonly World world;

View File

@@ -95,7 +95,7 @@ namespace OpenRA.Mods.Common.Traits
Info.ConstructionYardTypes.Contains(a.Info.Name))
.RandomOrDefault(World.LocalRandom);
return randomConstructionYard != null ? randomConstructionYard.Location : initialBaseCenter;
return randomConstructionYard?.Location ?? initialBaseCenter;
}
public readonly World World;

View File

@@ -59,8 +59,7 @@ namespace OpenRA.Mods.Common.Traits
public static string GetInitialFaction(ActorInfo ai, string defaultFaction)
{
var bi = ai.TraitInfoOrDefault<BuildableInfo>();
return bi != null ? bi.ForceFaction ?? defaultFaction : defaultFaction;
return ai.TraitInfoOrDefault<BuildableInfo>()?.ForceFaction ?? defaultFaction;
}
}

View File

@@ -65,14 +65,14 @@ namespace OpenRA.Mods.Common.Traits
protected static object LoadFootprint(MiniYaml yaml)
{
var footprintYaml = yaml.Nodes.FirstOrDefault(n => n.Key == "Footprint");
var footprintChars = footprintYaml != null ? footprintYaml.Value.Value.Where(x => !char.IsWhiteSpace(x)).ToArray() : new[] { 'x' };
var footprintChars = footprintYaml?.Value.Value.Where(x => !char.IsWhiteSpace(x)).ToArray() ?? new[] { 'x' };
var dimensionsYaml = yaml.Nodes.FirstOrDefault(n => n.Key == "Dimensions");
var dim = dimensionsYaml != null ? FieldLoader.GetValue<CVec>("Dimensions", dimensionsYaml.Value.Value) : new CVec(1, 1);
if (footprintChars.Length != dim.X * dim.Y)
{
var fp = footprintYaml.Value.Value.ToString();
var fp = footprintYaml.Value.Value;
var dims = dim.X + "x" + dim.Y;
throw new YamlException("Invalid footprint: {0} does not match dimensions {1}".F(fp, dims));
}

View File

@@ -104,7 +104,7 @@ namespace OpenRA.Mods.Common.Traits
if (Info.SourceCap > 0)
{
var timedCount = timedTokens.Count(t => t.Source == source);
if ((permanent != null ? permanent.Count + timedCount : timedCount) >= Info.SourceCap)
if ((permanent?.Count ?? 0) + timedCount >= Info.SourceCap)
{
// Get timed token from the same source with closest expiration.
var expireIndex = timedTokens.FindIndex(t => t.Source == source);

View File

@@ -43,7 +43,7 @@ namespace OpenRA.Mods.Common.Traits
actor =>
{
var init = actor.GetInitOrDefault<HealthInit>();
return init != null ? init.Value : 100;
return init?.Value ?? 100;
},
(actor, value) => actor.ReplaceInit(new HealthInit((int)value)));
}

View File

@@ -139,7 +139,7 @@ namespace OpenRA.Mods.Common.Traits
actor =>
{
var init = actor.GetInitOrDefault<FacingInit>(this);
return (init != null ? init.Value : InitialFacing).Angle;
return (init?.Value ?? InitialFacing).Angle;
},
(actor, value) => actor.ReplaceInit(new FacingInit(new WAngle((int)value))));
}

View File

@@ -60,7 +60,7 @@ namespace OpenRA.Mods.Common.Traits
var exploredMap = init.World.LobbyInfo.GlobalSettings.OptionOrDefault("explored", shroudInfo.ExploredMapCheckboxEnabled);
startsRevealed = exploredMap && init.Contains<SpawnedByMapInit>() && !init.Contains<HiddenUnderFogInit>();
var buildingInfo = init.Self.Info.TraitInfoOrDefault<BuildingInfo>();
var footprintCells = buildingInfo != null ? buildingInfo.FrozenUnderFogTiles(init.Self.Location).ToList() : new List<CPos>() { init.Self.Location };
var footprintCells = buildingInfo?.FrozenUnderFogTiles(init.Self.Location).ToList() ?? new List<CPos>() { init.Self.Location };
footprint = footprintCells.SelectMany(c => map.ProjectedCellsCovering(c.ToMPos(map))).ToArray();
}

View File

@@ -78,9 +78,9 @@ namespace OpenRA.Mods.Common.Traits
var myTeam = self.World.LobbyInfo.ClientWithIndex(self.Owner.ClientIndex).Team;
var teams = self.World.Players.Where(p => !p.NonCombatant && p.Playable)
.Select(p => (Player: p, PlayerStatistics: p.PlayerActor.TraitOrDefault<PlayerStatistics>()))
.OrderByDescending(p => p.PlayerStatistics != null ? p.PlayerStatistics.Experience : 0)
.OrderByDescending(p => p.PlayerStatistics?.Experience ?? 0)
.GroupBy(p => (self.World.LobbyInfo.ClientWithIndex(p.Player.ClientIndex) ?? new Session.Client()).Team)
.OrderByDescending(g => g.Sum(gg => gg.PlayerStatistics != null ? gg.PlayerStatistics.Experience : 0));
.OrderByDescending(g => g.Sum(gg => gg.PlayerStatistics?.Experience ?? 0));
if (teams.First().Key == myTeam && (myTeam != 0 || teams.First().First().Player == self.Owner))
{

View File

@@ -91,7 +91,7 @@ namespace OpenRA.Mods.Common.Traits
}
var producer = queue.MostLikelyProducer();
var faction = producer.Trait != null ? producer.Trait.Faction : self.Owner.Faction.InternalName;
var faction = producer.Trait?.Faction ?? self.Owner.Faction.InternalName;
var buildingInfo = actorInfo.TraitInfo<BuildingInfo>();
var buildableInfo = actorInfo.TraitInfoOrDefault<BuildableInfo>();

View File

@@ -116,9 +116,9 @@ namespace OpenRA.Mods.Common.Traits
var myTeam = self.World.LobbyInfo.ClientWithIndex(self.Owner.ClientIndex).Team;
var teams = self.World.Players.Where(p => !p.NonCombatant && p.Playable)
.Select(p => (Player: p, PlayerStatistics: p.PlayerActor.TraitOrDefault<PlayerStatistics>()))
.OrderByDescending(p => p.PlayerStatistics != null ? p.PlayerStatistics.Experience : 0)
.OrderByDescending(p => p.PlayerStatistics?.Experience ?? 0)
.GroupBy(p => (self.World.LobbyInfo.ClientWithIndex(p.Player.ClientIndex) ?? new Session.Client()).Team)
.OrderByDescending(g => g.Sum(gg => gg.PlayerStatistics != null ? gg.PlayerStatistics.Experience : 0));
.OrderByDescending(g => g.Sum(gg => gg.PlayerStatistics?.Experience ?? 0));
if (teams.First().Key == myTeam && (myTeam != 0 || teams.First().First().Player == self.Owner))
{

View File

@@ -63,7 +63,7 @@ namespace OpenRA.Mods.Common.Traits
actor =>
{
var init = actor.GetInitOrDefault<PlugInit>(this);
return init != null ? init.Value : "";
return init?.Value ?? "";
},
(actor, value) =>
{

View File

@@ -82,7 +82,7 @@ namespace OpenRA.Mods.Common.Traits.Render
{
body = self.Trait<BodyOrientation>();
facing = self.TraitOrDefault<IFacing>();
cachedFacing = facing != null ? facing.Facing : WAngle.Zero;
cachedFacing = facing?.Facing ?? WAngle.Zero;
cachedPosition = self.CenterPosition;
base.Created(self);
@@ -126,14 +126,14 @@ namespace OpenRA.Mods.Common.Traits.Render
var pos = Info.Type == TrailType.CenterPosition ? spawnPosition + body.LocalToWorld(offsetRotation) :
self.World.Map.CenterOfCell(spawnCell);
var spawnFacing = Info.SpawnAtLastPosition ? cachedFacing : (facing != null ? facing.Facing : WAngle.Zero);
var spawnFacing = Info.SpawnAtLastPosition ? cachedFacing : facing?.Facing ?? WAngle.Zero;
if ((Info.TerrainTypes.Count == 0 || Info.TerrainTypes.Contains(type)) && !string.IsNullOrEmpty(Info.Image))
self.World.AddFrameEndTask(w => w.Add(new SpriteEffect(pos, spawnFacing, self.World, Info.Image,
Info.Sequences.Random(Game.CosmeticRandom), Info.Palette, Info.VisibleThroughFog)));
cachedPosition = self.CenterPosition;
cachedFacing = facing != null ? facing.Facing : WAngle.Zero;
cachedFacing = facing?.Facing ?? WAngle.Zero;
ticks = 0;
cachedInterval = isMoving ? Info.MovingInterval : Info.StationaryInterval;

View File

@@ -40,7 +40,7 @@ namespace OpenRA.Mods.Common.Traits.Render
public RenderDebugState(Actor self, RenderDebugStateInfo info)
{
var buildingInfo = self.Info.TraitInfoOrDefault<BuildingInfo>();
var yOffset = buildingInfo == null ? 1 : buildingInfo.Dimensions.Y;
var yOffset = buildingInfo?.Dimensions.Y ?? 1;
offset = new WVec(0, 512 * yOffset, 0);
this.self = self;

View File

@@ -60,7 +60,7 @@ namespace OpenRA.Mods.Common.Traits.Render
if (facings == -1)
{
var qbo = init.Actor.TraitInfoOrDefault<IQuantizeBodyOrientationInfo>();
facings = qbo != null ? qbo.QuantizedBodyFacings(init.Actor, sequenceProvider, faction) : 1;
facings = qbo?.QuantizedBodyFacings(init.Actor, sequenceProvider, faction) ?? 1;
}
}
@@ -127,7 +127,7 @@ namespace OpenRA.Mods.Common.Traits.Render
// Return to the caller whether the renderable position or size has changed
var visible = IsVisible;
var offset = Animation.OffsetFunc != null ? Animation.OffsetFunc() : WVec.Zero;
var offset = Animation.OffsetFunc?.Invoke() ?? WVec.Zero;
var sequence = Animation.Animation.CurrentSequence;
var updated = visible != cachedVisible || offset != cachedOffset || sequence != cachedSequence;

View File

@@ -93,7 +93,7 @@ namespace OpenRA.Mods.Common.Traits.Render
{
// Return to the caller whether the renderable position or size has changed
var visible = model.IsVisible;
var offset = model.OffsetFunc != null ? model.OffsetFunc() : WVec.Zero;
var offset = model.OffsetFunc?.Invoke() ?? WVec.Zero;
var updated = visible != cachedVisible || offset != cachedOffset;
cachedVisible = visible;

View File

@@ -52,9 +52,13 @@ namespace OpenRA.Mods.Common.Traits
if (IsTraitDisabled || !correctFaction)
return;
var buildingInfo = self.Info.TraitInfoOrDefault<BuildingInfo>();
if (buildingInfo == null)
return;
var csv = self.Info.TraitInfoOrDefault<CustomSellValueInfo>();
var valued = self.Info.TraitInfoOrDefault<ValuedInfo>();
var cost = csv != null ? csv.Value : (valued != null ? valued.Cost : 0);
var cost = csv?.Value ?? valued?.Cost ?? 0;
var health = self.TraitOrDefault<IHealth>();
var dudesValue = Info.ValuePercent * cost / 100;
@@ -67,16 +71,14 @@ namespace OpenRA.Mods.Common.Traits
dudesValue = 0;
}
var buildingInfo = self.Info.TraitInfoOrDefault<BuildingInfo>();
var eligibleLocations = buildingInfo != null ? buildingInfo.Tiles(self.Location).ToList() : new List<CPos>();
var eligibleLocations = buildingInfo.Tiles(self.Location).ToList();
var actorTypes = Info.ActorTypes.Select(a =>
{
var av = self.World.Map.Rules.Actors[a].TraitInfoOrDefault<ValuedInfo>();
return new
{
Name = a,
Cost = av != null ? av.Cost : 0
Cost = av?.Cost ?? 0
};
}).ToList();

View File

@@ -153,7 +153,7 @@ namespace OpenRA.Mods.Common.Traits
{
var ios = actor.TraitInfoOrDefault<IOccupySpaceInfo>();
var buildingInfo = ios as BuildingInfo;
actorCenterOffset = buildingInfo != null ? buildingInfo.CenterOffset(world) : WVec.Zero;
actorCenterOffset = buildingInfo?.CenterOffset(world) ?? WVec.Zero;
actorSharesCell = ios != null && ios.SharesCell;
actorSubCell = SubCell.Invalid;

View File

@@ -239,7 +239,7 @@ namespace OpenRA.Mods.Common.Traits
void WorldOnRenderPlayerChanged(Player player)
{
var newShroud = player != null ? player.Shroud : null;
var newShroud = player?.Shroud;
if (shroud != newShroud)
{

View File

@@ -60,7 +60,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
var variant = resource.Sequences.FirstOrDefault();
var sequence = rules.Sequences.GetSequence("resources", variant);
var frame = sequence.Frames != null ? sequence.Frames.Last() : resource.MaxDensity - 1;
var frame = sequence.Frames?.Last() ?? resource.MaxDensity - 1;
layerPreview.GetSprite = () => sequence.GetSprite(frame);
layerPreview.Bounds.Width = tileSize.Width;

View File

@@ -118,7 +118,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
if (selectedDirectory == null)
selectedDirectory = writableDirectories.OrderByDescending(kv => kv.Classification).First();
directoryDropdown.GetText = () => selectedDirectory == null ? "" : selectedDirectory.DisplayName;
directoryDropdown.GetText = () => selectedDirectory?.DisplayName ?? "";
directoryDropdown.OnClick = () =>
directoryDropdown.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 210, writableDirectories, setupItem);
}

View File

@@ -38,7 +38,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
return;
var tooltip = armyUnit.TooltipInfo;
var name = tooltip != null ? tooltip.Name : armyUnit.ActorInfo.Name;
var name = tooltip?.Name ?? armyUnit.ActorInfo.Name;
var buildable = armyUnit.BuildableInfo;
nameLabel.Text = name;

View File

@@ -67,9 +67,9 @@ namespace OpenRA.Mods.Common.Widgets.Logic
var teams = world.Players.Where(p => !p.NonCombatant && p.Playable)
.Select(p => (Player: p, PlayerStatistics: p.PlayerActor.TraitOrDefault<PlayerStatistics>()))
.OrderByDescending(p => p.PlayerStatistics != null ? p.PlayerStatistics.Experience : 0)
.OrderByDescending(p => p.PlayerStatistics?.Experience ?? 0)
.GroupBy(p => (world.LobbyInfo.ClientWithIndex(p.Player.ClientIndex) ?? new Session.Client()).Team)
.OrderByDescending(g => g.Sum(gg => gg.PlayerStatistics != null ? gg.PlayerStatistics.Experience : 0));
.OrderByDescending(g => g.Sum(gg => gg.PlayerStatistics?.Experience ?? 0));
foreach (var t in teams)
{
@@ -111,7 +111,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
}
var scoreCache = new CachedTransform<int, string>(s => s.ToString());
item.Get<LabelWidget>("SCORE").GetText = () => scoreCache.Update(p.PlayerStatistics != null ? p.PlayerStatistics.Experience : 0);
item.Get<LabelWidget>("SCORE").GetText = () => scoreCache.Update(p.PlayerStatistics?.Experience ?? 0);
playerPanel.AddChild(item);
}

View File

@@ -52,7 +52,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
if (status == null && shouldShowStatus())
return statusText();
var timeLimit = tlm != null ? tlm.TimeLimit : 0;
var timeLimit = tlm?.TimeLimit ?? 0;
var displayTick = timeLimit > 0 ? timeLimit - world.WorldTick : world.WorldTick;
return WidgetUtils.FormatTime(Math.Max(0, displayTick), timestep);
};

View File

@@ -119,7 +119,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
var moi = world.Map.Rules.Actors["player"].TraitInfoOrDefault<MissionObjectivesInfo>();
if (moi != null)
{
var faction = world.LocalPlayer == null ? null : world.LocalPlayer.Faction.InternalName;
var faction = world.LocalPlayer?.Faction.InternalName;
Game.Sound.PlayNotification(world.Map.Rules, null, "Speech", moi.LeaveNotification, faction);
}
}
@@ -127,7 +127,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
leaving = true;
var iop = world.WorldActor.TraitsImplementing<IObjectivesPanel>().FirstOrDefault();
var exitDelay = iop != null ? iop.ExitDelay : 0;
var exitDelay = iop?.ExitDelay ?? 0;
if (mpe != null)
{
Game.RunAfterDelay(exitDelay, () =>
@@ -208,7 +208,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
return;
var iop = world.WorldActor.TraitsImplementing<IObjectivesPanel>().FirstOrDefault();
var exitDelay = iop != null ? iop.ExitDelay : 0;
var exitDelay = iop?.ExitDelay ?? 0;
Action onRestart = () =>
{

View File

@@ -41,7 +41,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
if (world.LocalPlayer.WinState != WinState.Undefined && !loadingObserverWidgets)
{
loadingObserverWidgets = true;
Game.RunAfterDelay(objectives != null ? objectives.GameOverDelay : 0, () =>
Game.RunAfterDelay(objectives?.GameOverDelay ?? 0, () =>
{
if (!Game.IsCurrentWorld(world))
return;

View File

@@ -49,26 +49,24 @@ namespace OpenRA.Mods.Common.Widgets.Logic
ActorInfo lastActor = null;
Hotkey lastHotkey = Hotkey.Invalid;
var lastPowerState = pm == null ? PowerState.Normal : pm.PowerState;
var lastPowerState = pm?.PowerState ?? PowerState.Normal;
var descLabelY = descLabel.Bounds.Y;
var descLabelPadding = descLabel.Bounds.Height;
tooltipContainer.BeforeRender = () =>
{
var tooltipIcon = getTooltipIcon();
if (tooltipIcon == null)
return;
var actor = tooltipIcon.Actor;
var actor = tooltipIcon?.Actor;
if (actor == null)
return;
var hotkey = tooltipIcon.Hotkey != null ? tooltipIcon.Hotkey.GetValue() : Hotkey.Invalid;
var hotkey = tooltipIcon.Hotkey?.GetValue() ?? Hotkey.Invalid;
if (actor == lastActor && hotkey == lastHotkey && (pm == null || pm.PowerState == lastPowerState))
return;
var tooltip = actor.TraitInfos<TooltipInfo>().FirstOrDefault(info => info.EnabledByDefault);
var name = tooltip != null ? tooltip.Name : actor.Name;
var name = tooltip?.Name ?? actor.Name;
var buildable = actor.TraitInfo<BuildableInfo>();
var cost = 0;
@@ -125,7 +123,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
powerSize = font.Measure(powerLabel.Text);
}
var buildTime = tooltipIcon.ProductionQueue == null ? 0 : tooltipIcon.ProductionQueue.GetBuildTime(actor, buildable);
var buildTime = tooltipIcon.ProductionQueue?.GetBuildTime(actor, buildable) ?? 0;
var timeModifier = pm != null && pm.PowerState != PowerState.Normal ? tooltipIcon.ProductionQueue.Info.LowPowerModifier : 100;
timeLabel.Text = formatBuildTime.Update((buildTime * timeModifier) / 100);

View File

@@ -49,7 +49,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
// to efficiently work when the label is going to change, requiring a panel relayout
var remainingSeconds = (int)Math.Ceiling(sp.RemainingTicks * world.Timestep / 1000f);
var hotkey = icon.Hotkey != null ? icon.Hotkey.GetValue() : Hotkey.Invalid;
var hotkey = icon.Hotkey?.GetValue() ?? Hotkey.Invalid;
if (sp == lastPower && hotkey == lastHotkey && lastRemainingSeconds == remainingSeconds)
return;