Invariant code contracts – using class-wide contracts

It is possible to define invariant code contracts for classes. Invariant contracts should always hold true whatever member of class is called. In this posting I will show you how to use invariant code contracts so you understand how they work and how they should be tested.

This is my randomizer class I am using to demonstrate code contracts. I added one method for invariant code contracts. Currently there is one contract that makes sure that random number generator is not null.

public class Randomizer
{
   
private IRandomGenerator
_generator;

   
private
Randomizer() { }

   
public Randomizer(IRandomGenerator
generator)
    {
        _generator = generator;
    }

   
public int GetRandomFromRangeContracted(int min, int
max)
    {
       
Contract.Requires<ArgumentOutOfRangeException
>(
            min < max,
           
"Min must be less than max"
        );

       
Contract
.Ensures(
           
Contract.Result<int
>() >= min &&
           
Contract.Result<int
>() <= max,
           
"Return value is out of range"
        );

       
return
_generator.Next(min, max);
    }

    [
ContractInvariantMethod
]
   
private void
ObjectInvariant()
    {
       
Contract.Invariant(_generator != null);
    }
}

Invariant code contracts are define in methods that have ContractInvariantMethod attribute. Some notes:

  • It is good idea to define invariant methods as private.
  • Don’t call invariant methods from your code because code contracts system does not allow it.
  • Invariant methods are defined only as place where you can keep invariant contracts.
  • Invariant methods are called only when call to some class member is made!

The last note means that having invariant method and creating Randomizer object with null as argument does not automatically generate exception. We have to call at least one method from Randomizer class.

Here is the test for generator. You can find more about contracted code testing from my posting Code Contracts: Unit testing contracted code. There is also explained why the exception handling in test is like it is.

[TestMethod]
[
ExpectedException(typeof(Exception))]
public void
Should_fail_if_generator_is_null()
{
   
try
    {
       
var randomizer = new Randomizer(null
);
        randomizer.GetRandomFromRangeContracted(1, 4);
    }
   
catch (Exception
ex)
    {
       
throw new Exception(ex.Message, ex);
    }
}

Try out this code – with unit tests or with test application to see that invariant contracts are checked as soon as you call some member of Randomizer class.

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    50 thoughts on “Invariant code contracts – using class-wide contracts

    • April 13, 2025 at 2:37 pm
      Permalink

      What if your website gunnarpeipman.com could instantly receive a significant surge in traffic? Many businesses overlook thousands of daily visitors simply because they don’t have enough exposure.

      With our AI-powered traffic solution, you can attract 4,000 highly targeted visitors as part of a free trial. If you like what you see, our plans can deliver 350K visitors monthly—helping your site grow. Get more details here: https://ow.ly/W8hy50Vvbm9

    • April 14, 2025 at 12:10 pm
      Permalink

      Every day, websites like gunnarpeipman.com fail to capture valuable traffic opportunities. Don’t let yours be one of them. Our automated traffic system is designed to enhance engagement and bring highly targeted traffic to your site.

      Claim your 4,000 free visitors to test the benefits firsthand. Then, scale up to plans offering up to 350,000 visitors per month. It’s time to realize your website’s true traffic potential. Get started here: https://ow.ly/wlFl50VyXZ8

    • April 15, 2025 at 4:17 am
      Permalink

      Get more leads for your gunnarpeipman.com website by using AI on Instagram. If you’re looking to drive more traffic, generate leads, and grow your brand’s reach, you can get more information and start a free trial here: https://ow.ly/1Yh050VyYcH

      This is an AI-powered Instagram growth service that:
      -Increases followers with targeted, high-quality audiences.
      -Boosts engagement through smart AI algorithms.
      -Targets users based on hashtags and accounts they follow.
      -Saves you time by automating tedious Instagram tasks.

      Our service focuses on real, organic growth—no bots, no fake followers. It’s perfect for brands like yours that want to turn Instagram into a lead generation powerhouse. Better yet, our service is provided on a month-by-month subscription basis so you can cancel any time you like. No contracts and a 7 day free trial.

    • April 15, 2025 at 6:59 am
      Permalink

      Is your website gunnarpeipman.com overlooking its true potential? With our automated traffic system, you might be able to connect with thousands of additional visitors daily—without any extra effort on your part.

      Take advantage of our complimentary offer that delivers 4,000 visitors so you can test the impact. If you love the results, our plans scale up to 350,000 visitors per month. Let’s turn missed opportunities into growth. Get more details here: https://ow.ly/zcWz50VyY3y

    • April 15, 2025 at 8:24 pm
      Permalink

      Wanting to amplify your website growth? Our AI-driven system delivers custom website traffic using keywords and geographic precision from continents to towns.
      Looking to increased revenue, boosted visitors, or greater digital impact?
      We customize it to match your needs. Enjoy a 7-day free trial period with no contract. Dive in here:

      https://ow.ly/u8pX50VyY2P

    • April 16, 2025 at 5:50 pm
      Permalink

      Every day, websites like gunnarpeipman.com miss valuable traffic opportunities. Don’t let yours be one of them. Our smart traffic system is designed to increase exposure and bring potential customers to your site.

      Claim your 4,000 free visitors to experience the benefits firsthand. Then, expand to plans offering up to 350K visitors per month. It’s time to unlock your website’s true traffic potential. Get started here: https://ow.ly/qsrO50VyY7j

    • April 16, 2025 at 11:08 pm
      Permalink

      Working to power your website traffic? Our smart AI tool delivers targeted website traffic using keywords or location zones from continents to neighborhoods.
      Seeking higher earnings, active website traffic, or a wider digital presence?
      We shape it to match your strategy. Enjoy a 7-day free trial period with no contract. Join now:

      https://ow.ly/PZIo50VyY6U

    • April 17, 2025 at 9:13 pm
      Permalink

      Get more leads for your gunnarpeipman.com website by using AI on Instagram. If you’re looking to drive more traffic, generate leads, and grow your brand’s reach, you can get more information and start a free trial here: https://ow.ly/K7b550VyYeE

      This is an AI-powered Instagram growth service that:
      -Increases followers with targeted, high-quality audiences.
      -Boosts engagement through smart AI algorithms.
      -Targets users based on hashtags and accounts they follow.
      -Saves you time by automating tedious Instagram tasks.

      Our service focuses on real, organic growth—no bots, no fake followers. It’s perfect for brands like yours that want to turn Instagram into a lead generation powerhouse. Better yet, our service is provided on a month-by-month subscription basis so you can cancel any time you like. No contracts and a 7 day free trial.

    • April 19, 2025 at 1:52 am
      Permalink

      What if your website gunnarpeipman.com could instantly receive a significant surge in traffic? Many businesses fail to attract thousands of daily visitors simply because they don’t have enough exposure.

      With our AI-powered traffic solution, you can get 4,000 highly targeted visitors as part of a free trial. If you like what you see, our plans can deliver 350,000 visitors monthly—helping your site expand. Get more details here: https://ow.ly/ZNA050Vycl9

    • April 19, 2025 at 8:19 pm
      Permalink

      Use AI to drive targeted traffic to your website for free with our brand new service. Get Free Google Analytics set up, real traffic, and target any location on Earth here: https://cutt.ly/SrgOJvYE

    • April 20, 2025 at 12:21 am
      Permalink

      What if your website gunnarpeipman.com was guaranteed a huge surge in traffic? Many businesses miss out on thousands of daily visitors simply because they lack the right reach.

      With our AI-powered traffic solution, you can receive 4,000 highly targeted visitors as part of a no-risk test. If you like what you see, our plans scale to 350K visitors monthly—helping your site flourish. Get more details here: https://ow.ly/PZvj50VyclK

    • April 21, 2025 at 8:48 pm
      Permalink

      Is your gunnarpeipman.com website maximizing its reach? Many websites overlook thousands of visitors daily due to lack of exposure. With our cutting-edge traffic solution, you can unlock a much larger audience.

      To show you the impact, we’re offering a complimentary trial that delivers 4,000 highly targeted visitors to your website. See the results firsthand, and then scale up to 350,000 visitors per month with our advanced packages. Let’s boost your website’s traffic and turn visitors into growth. Get more info here: https://ow.ly/Qr2O50Vycs2

    • April 23, 2025 at 5:57 am
      Permalink

      Get additional leads for your gunnarpeipman.com website by using AI on Instagram. If you’re looking to increase more traffic, generate leads, and grow your brand’s reach, you can get more information and start a complimentary trial here: https://ow.ly/IQrK50VycMg

      This is an AI-powered Instagram growth service that:
      -Increases followers with focused, high-quality audiences.
      -Boosts engagement through advanced AI algorithms.
      -Targets users based on hashtags and accounts they follow.
      -Eliminates work by automating repetitive Instagram tasks.

      Our service emphasizes on authentic, organic growth—without bots, zero fake followers. It’s excellent for brands like yours that want to turn Instagram into a lead generation engine. Best of all, our service is provided on a month-by-month subscription basis so you can stop whenever you like. No contracts and a 7-day free trial.

    • April 23, 2025 at 9:23 am
      Permalink

      Is your gunnarpeipman.com website getting the traffic it deserves? Many websites lose thousands of visitors daily due to lack of exposure. With our AI-powered traffic solution, you can tap into a much larger audience.

      To show you the impact, we’re offering a complimentary trial that delivers 4,000 highly targeted visitors to your website. See the results firsthand, and then scale up to 350K visitors per month with our advanced packages. Let’s supercharge your website’s traffic and turn visitors into results. Get more info here: https://ow.ly/I70p50Vycvl

    • April 24, 2025 at 10:34 am
      Permalink

      Is your website gunnarpeipman.com failing to capture its true potential? With our intelligent traffic system, you might be able to connect with thousands of additional visitors daily—without any extra effort on your part.

      Take advantage of our complimentary offer that delivers a 4,000-visitor boost so you can see the impact. If you love the results, our plans provide up to 350K visitors per month. Let’s turn missed opportunities into growth. Get more details here: https://ow.ly/zyag50VycwY

    • April 26, 2025 at 9:38 pm
      Permalink

      Get more leads for your gunnarpeipman.com website by harnessing AI on Instagram. If you’re looking to increase enhanced traffic, generate leads, and grow your brand’s reach, you can get more information and start a free trial here: https://ow.ly/uO0I50VycOz

      This is an AI-powered Instagram growth service that:
      -Boosts followers with focused, high-quality audiences.
      -Boosts engagement through smart AI algorithms.
      -Focuses on users based on hashtags and accounts they follow.
      -Reduces effort by automating repetitive Instagram tasks.

      Our service prioritizes on real, organic growth—without bots, zero fake followers. It’s excellent for brands like yours that want to transform Instagram into a lead generation machine. Even better, our service is provided on a monthly subscription basis so you can stop any time you like. No contracts and a one-week no-cost trial.

    • April 30, 2025 at 8:02 pm
      Permalink

      Attract increased leads for your gunnarpeipman.com website by harnessing AI on Instagram. If you’re looking to boost more traffic, generate leads, and expand your brand’s reach, you can get more information and start a no-cost trial here: https://ow.ly/lq4z50VycPA

      This is an AI-powered Instagram growth service that:
      -Increases followers with targeted, premium audiences.
      -Enhances engagement through intelligent AI algorithms.
      -Aims at users based on hashtags and accounts they follow.
      -Reduces time by automating time-consuming Instagram tasks.

      Our service focuses on genuine, organic growth—no bots, without fake followers. It’s ideal for brands like yours that want to turn Instagram into a lead generation machine. Even better, our service is provided on a month-by-month subscription basis so you can cancel whenever you like. No contracts and a 7 day complimentary trial.

    • May 5, 2025 at 4:20 am
      Permalink

      Is your website gunnarpeipman.com missing out on its true potential? With our intelligent traffic system, you could connect with thousands of additional visitors daily—without any extra effort on your part.

      Take advantage of our free trial that delivers four thousand targeted visitors so you can see the impact. If you love the results, our plans offer up to 350,000 visitors per month. Let’s realize untapped potential for growth. Get more details here: https://ow.ly/rOBx50VycBp

    • May 7, 2025 at 6:14 pm
      Permalink

      Attract more leads for your gunnarpeipman.com website by using AI on Instagram. If you’re looking to drive enhanced traffic, produce leads, and grow your brand’s reach, you can get more information and start a no-cost trial here: https://ow.ly/9Kr350VycQU

      This is an AI-powered Instagram growth service that:
      -Increases followers with targeted, top-tier audiences.
      -Boosts engagement through intelligent AI algorithms.
      -Aims at users based on hashtags and accounts they follow.
      -Saves work by automating time-consuming Instagram tasks.

      Our service emphasizes on genuine, organic growth—no bots, no fake followers. It’s ideal for brands like yours that want to convert Instagram into a lead generation machine. Even better, our service is provided on a month-by-month subscription basis so you can cancel whenever you like. No contracts and a one-week no-cost trial.

    • May 19, 2025 at 3:15 pm
      Permalink

      Is your gunnarpeipman.com website maximizing its reach? Many websites overlook thousands of visitors daily due to not being optimized for reach. With our cutting-edge traffic solution, you can unlock a much larger audience.

      To show you the impact, we’re offering a free trial that delivers four thousand highly targeted visitors to your website. See the results firsthand, and then scale up to 350,000 visitors per month with our advanced packages. Let’s supercharge your website’s traffic and turn visitors into growth. Get more info here: https://ow.ly/3avx50VycEU

    • May 19, 2025 at 7:25 pm
      Permalink

      Use AI to drive targeted traffic to your website for free with our brand new service. Get Free Google Analytics set up, real traffic, and target any location on Earth here: https://cutt.ly/vrgOJtwE

    • May 22, 2025 at 10:49 am
      Permalink

      Not getting the social media traction you deserve? Let us simplify your social media and amplify your presence.
      Say goodbye to social media stress with our:
      Crafting and sharing 5 weekly posts customized to match your brand’s style and objectives.

      Leveraging our cutting-edge AI growth tools to boost your account’s visibility, interactions, and follower count.

      Imagine having a consistent, professional social media presence without lifting a finger. Our team handles everything from content creation to posting, while our cutting-edge AI ensures your account grows steadily.
      Ready to take your social media to the next level? Reply to this email or click https://cutt.ly/Irk0THq5 to schedule a quick chat to discover how we can make your brand stand out.

    • May 23, 2025 at 9:46 am
      Permalink

      Attract additional leads for your gunnarpeipman.com website by harnessing AI on Instagram. If you’re looking to boost enhanced traffic, produce leads, and expand your brand’s reach, you can find more information and start a free trial here: https://ow.ly/XBrW50VycRS

      This is an AI-powered Instagram growth service that:
      -Boosts followers with targeted, top-tier audiences.
      -Enhances engagement through smart AI algorithms.
      -Aims at users based on hashtags and accounts they follow.
      -Eliminates effort by automating time-consuming Instagram tasks.

      Our service prioritizes on authentic, organic growth—without bots, without fake followers. It’s ideal for brands like yours that want to turn Instagram into a lead generation powerhouse. Better yet, our service is provided on a monthly subscription basis so you can opt out at any point you like. No contracts and a one-week no-cost trial.

    • May 29, 2025 at 12:46 pm
      Permalink

      Is your website gunnarpeipman.com missing out on its true potential? With our intelligent traffic system, you might be able to engage thousands of additional visitors daily—without any extra effort on your part.

      Take advantage of our free trial that delivers four thousand targeted visitors so you can experience the impact. If you love the results, our plans offer up to 350,000 visitors per month. Let’s realize untapped potential for growth. Get more details here: https://cutt.ly/vrvBhW6k

    • May 30, 2025 at 8:05 am
      Permalink

      Use AI to build a website by just entering a few lines of text for free. Our AI powered system will then build an entire website in just a few minutes. Try it free here: https://ow.ly/X0fC50VqFE6

    • June 5, 2025 at 9:17 am
      Permalink

      Get increased leads for your gunnarpeipman.com website by leveraging AI on Instagram. If you’re looking to increase enhanced traffic, produce leads, and grow your brand’s reach, you can find more information and start a complimentary trial here: https://ow.ly/XBrW50VycRS

      This is an AI-powered Instagram growth service that:
      -Boosts followers with focused, premium audiences.
      -Improves engagement through smart AI algorithms.
      -Targets users based on hashtags and accounts they follow.
      -Eliminates time by automating time-consuming Instagram tasks.

      Our service prioritizes on genuine, organic growth—zero bots, no fake followers. It’s excellent for brands like yours that want to transform Instagram into a lead generation machine. Even better, our service is provided on a month-by-month subscription basis so you can stop whenever you like. No contracts and a one-week complimentary trial.

    • June 6, 2025 at 10:41 pm
      Permalink

      Every day, websites like gunnarpeipman.com lose valuable traffic opportunities. Don’t let yours be one of them. Our AI-powered traffic system is designed to enhance engagement and bring highly targeted traffic to your site.

      Claim your complimentary 4,000-visitor trial to experience the benefits firsthand. Then, expand to plans offering up to 350K visitors per month. It’s time to achieve your website’s true traffic potential. Get started here: https://cutt.ly/3rbmwGFS

    • June 9, 2025 at 5:58 pm
      Permalink

      Ready to unleash a flood of website traffic? Our AI-powered solution brings tailored visitors through keywords plus geographic zones from global areas to towns.
      Seeking more revenue, boosted visitors, or a wider digital presence?
      We adjust it to suit your objectives. Enjoy a 7-day free trial period with no contract. Join here:

      https://cutt.ly/OrnRcJu7

    • June 13, 2025 at 10:25 pm
      Permalink

      Every day, websites like gunnarpeipman.com lose valuable traffic opportunities. Don’t let yours be one of them. Our AI-powered traffic system is designed to increase exposure and bring potential customers to your site.

      Claim your 4,000 free visitors to test the benefits firsthand. Then, upgrade to plans offering up to 350K visitors per month. It’s time to achieve your website’s true traffic potential. Get started here: https://cutt.ly/yrmVkKHJ

    • June 15, 2025 at 7:17 pm
      Permalink

      Capture additional leads for your gunnarpeipman.com website by using AI on Instagram. If you’re looking to boost greater traffic, generate leads, and expand your brand’s reach, you can find more information and start a free trial here: https://ow.ly/aSLa50VycS2

      This is an AI-powered Instagram growth service that:
      -Increases followers with specific, premium audiences.
      -Boosts engagement through intelligent AI algorithms.
      -Aims at users based on hashtags and accounts they follow.
      -Reduces time by automating time-consuming Instagram tasks.

      Our service prioritizes on genuine, organic growth—zero bots, zero fake followers. It’s excellent for brands like yours that want to transform Instagram into a lead generation engine. Best of all, our service is provided on a flexible subscription basis so you can stop at any point you like. No contracts and a one-week no-cost trial.

    • June 18, 2025 at 1:02 pm
      Permalink

      Struggling to draw the right website traffic? Our AI-enhanced tool directs targeted visitors via keywords plus location filters from continents to local areas.
      Desiring higher revenue, active users, or wider digital reach?
      We fine-tune it to fit your strategy. Enjoy a 7-day free trial period with no contract. Start here:

      https://cutt.ly/mrQWZMPb

    Leave a Reply

    Your email address will not be published. Required fields are marked *