Check if class property is not null before calling any public class method

c# check if object property is null
how to check all properties of an object whether null or empty c#
c# check if object is null or empty
how to check all properties of an object whether null or empty java
c# check if property exists on dynamic
c# reflection get property value
c# remove null property from object
c# check if string is null

What I have: Game class (as a part of Laravel 5.5 framework)

class Game implements GameInterface
{
    private $currentGame;

    public function __construct()
    {
        $this->currentGame = Game::where('status', true)->first();
    }

    public function getPlayersAmount()
    {
        if ($this->currentGame)
            //fetch data & return it
        else
            return 0;
    }

    public function getPlayers()
    {
        if ($this->currentGame)
            //fetch data & return it
        else
            return null;
    }

    public function getAllStats()
    {
        if ($this->currentGame)
            //fetch data & return it
        else
            return null;
    }

    public function getTopScore()
    {
        if ($this->currentGame)
            //fetch data & return it
        else
            return 0;
    }
}

My problem - if ($this->currentGame). I have to place it inside each method to avoid Eloquent-related Exceptions.

How can I make this check if ($this->currentGame) before each method call to avoid code duplicate?

__call() doesn't work for public methods.

My current class usage:

$game = new Game();
$game->getPlayers();
//and so on

You can use __call with this, you will just need to make your public functions private - and then prefix them with something unique to make sure that they are the only private functions that can be publicly callable.

Here is an example.

class Game implements GameInterface
{
    private $currentGame;

    public function __construct()
    {
        $this->currentGame = Game::where('status', true)->first();
    }

    public function __call($method, $args)
    {
        if ($this->currentGame) 
            return call_user_func_array(array($this, 'public'.ucfirst($method)), $args);
        else 
            return 0;
    }

    private function publicGetPlayersAmount()
    {
        //fetch data & return it
    }

    private function publicGetPlayers()
    {
        //fetch data & return it
    }

    private function publicGetAllStats()
    {
        //fetch data & return it
    }

    private function publicGetTopScore()
    {
        //fetch data & return it
    }
}

Generic Null/Empty check for each property of a class, You do not need to declare a local variable for result , simply return its value where Property, AllowMultiple = false)] public abstract class ValidatorAttribute what happens when an object is first created without setting any // values), is null or is an GetValue(obj) != null) { // Make recursive call to this function defaultProps. Hello, I want to check to see if an object is null before calling its method. Am checking to see if the client is a proxy or direct IP using both HttpContext.Current.Request.ServerVariables["H


Your approach dos not makes a lot of sense, in my opinion.

If your Game instance will depend on having a currentGame, it should not be possible to create the instance if currentGame is falsey.

Just put the verification in the constructor and throw an exception if can't be instantiated.

public function __construct()
  {
    $this->currentGame = Game::where('status', true)->first();

    if (! $this->currentGame) {
        throw new \Exception('Current game not available');
        // probably better if you define your own exception class
    }
  }

Then you just check if this works on instantiation, and if it does continue normally:

try { 
    $game = new Game();
    $game->getPlayers();
}
catch (\Exception $e) {
    // $game is not safe to use, do something about it.
}

Pro Business Applications with Silverlight 5, For example, properties implemented in the following fashion do not raise the even when that class implements the INotifyPropertyChanged interface: public not be aware of any changes to the value of that property that it did not make event is not null, which it will be if nothing is handling the event, before calling it. The ?. is the null-propagating operator, and will cause the .Invoke() to be short-circuited when the operand is null. The operand is only accessed once, so there is no risk of the "value changes between check and invoke" problem.


I think it may be accomplished with __call and call_user_func_array

class Game implements GameInterface
{
    private $currentGame;

    public function __construct()
    {
        $this->currentGame = Game::where('status', true)->first();
    }

    public function __call($name, $arguments) {
        $name = '_'.$name;
        if ($this->currentGame && method_exists($this,$name)) return call_user_func_array(array($this, $name), $arguments);
        return null;
    }

    private function _getPlayersAmount()
    {
        return "sthg";
    }

    private function _getPlayers()
    {
        return "sthg else";
    }

    private function _getAllStats()
    {
        return "also sthg else";
    }

    private function _getTopScore()
    {
        return "different one";
    }
}

simply we implement our functions as private with slightly different name and let them called through __call via call_user_func_array. We could also use a switch-case as well, however this way it's more dynamic.

Learning Android Application Programming: A Hands-on Guide to , Save this in a new private property named timerService (see Listing 9.7). Listing 9.7 Connecting to the Timer Service private class TimerServiceConnection implements public void onServiceConnected(ComponentName className, IBinder service) In each method, check that timerService is not null before calling  Here is how it works. You decorate your properties with the 'Required' attribute. If you instantiate the containing class, and use it, you can call the static method Required.PerformCheck(object). At this time it will throw exceptions if an property is null, but you can do anything at that point.


Pro WPF and Silverlight MVVM: Effective Application Development , public partial class App : Application { private ApplicationViewModel This is why we check that the returned object is not null before calling any methods or contains an Args property, which is a string array of the supplied arguments. The print() method call would just print “null” but won't throw an exception. Similarly, process() would never return null in its response. It rather throws an Exception. So for a client code accessing the above APIs, there is no need for a null check. However, such APIs must make it explicit in their contract.


List<T>.Contains(T) Method, A PartId is used to identify a part // but the part name can change. public class Part + " Name: " + PartName; } public override bool Equals(object obj) { if (obj == null) This will call the overridden ToString method // in the Part class. Contains("seat"))); // Check if an item with Id 1444 exists. No. Any additional feedback? That is a bad practice. It is better to ensure that the value is not null. Method #4 will work for you. It will not evaluate the second condition, because Java has short-circuiting (i.e., subsequent conditions will not be evaluated if they do not change the end-result of the boolean expression).


Type.GetProperty Method (System), name is null . Examples. The following example retrieves the Type object of a user-defined class, retrieves a property of that class, and displays  Problem while calling java stored procedure which connects to db2. how to check if a pointer is unbound? Calling a thread asynchronously with a callback; How to get calling object type in static method of Base Class; How to check if a Mutex is already locked. Getting handle to calling dll/exe; Calling Class; MySQL/PHP: Check data length before